I'm trying to understand what means exactly declaring, defining and initialising of a variable.
let a; // If this is a declaration
let a = 22; // and this is initialising
how I define a variable?
can I initialise a function?
I'm trying to understand what means exactly declaring, defining and initialising of a variable.
let a; // If this is a declaration
let a = 22; // and this is initialising
how I define a variable?
can I initialise a function?
how I define a variable?
With a variable declaration. There is no distinction between defining a variable and declaring a variable. Well, okay, there's one case of defining but not declaring a variable: Assigning to an undeclared identifier in loose mode, which is what I call The Horror of Implicit Globals because it creates a global variable without any declaration. Don't do that. :-)
How I declare a function?
My answer here to another question lists the various ways you can create functions in JavaScript. One of those ways is a function declaration.
Some quick examples, but I doubt that question or that answer will get deleted:
Function Declaration:
function foo() {
}
Note we're not doing x =
in front of it. Anything that would great that as an expression would make it not a declaration anymore.
"Anonymous" function Expression (which despite the term, sometimes create functions with names):
x = function() { };
// ^^^^^^^^^^^^^^--- this is the expression
doSomethingWith(function() { });
// ^^^^^^^^^^^^^^--- this is the expression
Named function Expression
x = function foo() { };
// ^^^^^^^^^^^^^^^^^^--- this is the expression
doSomethingWith(function foo() { });
// ^^^^^^^^^^^^^^^^^^--- this is the expression
Accessor Function Initializer (ES5+):
obj = {
get foo() { // << This is an accessor, specifically a getter
}, // <<
set foo() { // << This is an accessor, specifically a setter
} // <<
}
Arrow Function Expression (ES2015+) (which, like anonymous function expressions, don't involve an explicit name, and yet can create functions with names); these can be verbose (with a { .. }
body) or concise (without {}
):
x = () => { };
// ^^^^^^^^^--- Verbose arrow function
doSomethingWith(() => { });
// ^^^^^^^^^--- another verbose arrow function
y = () => expressionGoesHere;
// ^^^^^^^^^^^^^^^^^^^^^^^^--- Concise arrow function
doSomethingWith(() => expressionGoesHere);
// ^^^^^^^^^^^^^^^^^^^^^^^^--- another concise arrow function
Method Declaration in Object Initializer (ES2015+)
obj = {
foo() { // << This is the method declaration
} // <<
};
Constructor and Method Declarations in class (ES2015+)
class Example {
foo() { // << This is the method declaration
} // <<
}
can I initialise a function?
You can initialize a variable (or property) with a reference to a function:
let a = function() { }; // Variable
someObject.b = function() { }; // Object property