-
Variables, Constants & Comments
In JavaScript, variables are used to store values that can be used later in your code. Constants are similar to variables, but their values cannot be changed once they are set. Comments are used to add notes to your code that are ignored by the JavaScript engine.
-
var
is a keyword in JavaScript that was used to declare variables prior to the introduction oflet
andconst
. Thevar
keyword has function scope, which means that a variable declared withvar
is accessible within the entire function in which it was declared, and can also be accessed within inner functions. One of the issues withvar
is that it is function scoped, but it also has a strange behavior called "hoisting". Hoisting refers to the behavior of moving variable and function declarations to the top of their respective scopes, which means that a variable declared withvar
can be used before it is declared in the code.console.log(x); // undefined var x = 10;
Even though
x
is declared after theconsole.log
statement, it still outputsundefined
instead of throwing a ReferenceError. This is because the declaration ofx
is hoisted to the top of the function and the assignment of10
remains in its original place. For these reasons, it's generally recommended to uselet
andconst
instead ofvar
when declaring variables in JavaScript.let
andconst
have block scope and do not exhibit the hoisting behavior ofvar
-
Variables: Variables are containers for storing data values. In JavaScript, you can declare a variable using the
var
,let
, orconst
keyword. The difference betweenvar
andlet
is thatvar
has function scope whilelet
has block scope. Theconst
keyword is used to declare a constant that cannot be reassigned after it has been declared.let name = 'John Doe'; const PI = 3.14;
-
Constants: Constants are similar to variables, but their value cannot be changed once it has been assigned. In JavaScript, you can declare a constant using the
const
keyword.const PI = 3.14;
-
Comments: Comments are used to add annotations and explanations to your code. They are ignored by the JavaScript interpreter and are only intended to be read by developers. In JavaScript, you can create single-line comments using
//
and multi-line comments using/* */
.// This is a single-line comment /* This is a multi-line comment */
-