Musa Muaz
Musa Muaz

Reputation: 714

function is called as a non function in javascript

My website needs to convert its nav menu when it is in a viewport which size is less than 800px.More over I have made a plugin for this and that plugin also provide vertical nav options.So i want to apply that vertical nav when it is in viewport less than 800px.

My codes for vertical nav

if(verticalNav){
   menuConvert()
}

And when in less than 800px

if($(window).width < 800){
   menuConvert()
}

And menuConvert function is

var menuConvert = function(){
     // codes here
}

But in console log: menuConvert is not a function

Any solution for that?

Upvotes: 1

Views: 279

Answers (2)

6502
6502

Reputation: 114481

In Javascript there is a difference between

var a = function() { ... };

and

function a() { ... }

The first is an assignment and is executed where the statement is met during the normal execution flow. This means for example that you cannot call a() before it has been set to be a function/closure.

The second is instead a function declaration and for example code like

console.log(b());
function b() { return 42; }

is valid.

Upvotes: 0

Zee
Zee

Reputation: 8488

var menuConvert = function(){
     // codes here
}

should be PLACED above

if($(window).width < 800){
 menuConvert();
}

OR change assignment to simple function like this:

function menuConvert(){
   console.log("Hello")
}

and it should work. The reason is JavaScript only hoists declarations, not initializations.

Upvotes: 3

Related Questions