JSFiddle - React, Tailwind, and code Playground
by Gonzalo
JavaScript
/*
Declaring Variables and Functions
Variables can be defined with the var statement, and are initialised to undefined:
*/
var a; // undefined
var b = 'hello';
/*
The scoping of these statements is dependent on where they’re declared. If var statements don’t appear inside a function, they’re globally accessible:
*/
var a = 1;
function sum(b) {
return a + b;
}
/*
Missing var
Problems start to occur when a var statement is forgotten:
*/
function example() {
a = 1;
b = 1;
return a + b;
}
/*
These variables are not local to the example function, they’re actually global. If a or b already existed, then their values will be overwritten.
Accidentally leaving out a var statement is surprisingly easy, and could potentially cause irritating bugs.
*/
/*
Variable Declaration Styles
Some people like to group var statements together:
*/
var a = 1,
b = 2,
c = 3;
/*
What would happen if a comma was missed by mistake?
*/
function example() {
var a = 1
b = 2,
c = 3;
}
example();
console.log(typeof a);
console.log(typeof b);
console.log(typeof c);
/*
Running this will show that while a is undefined and therefore local to example, the other variables are global.
The reason some developers place commas before lists of variable declarations is to make it easier to see if a comma has been forgotten:
*/
var a = 1
, b = 2
, c = 3
;