JavaScript syntax: Difference between revisions

Content deleted Content added
Replacement of 'var' with 'let' or 'const'.
Line 92:
 
==Variables==
[[Variable (programming)|Variable]]s in standard JavaScript have no [[Type system|type]] attached, so any value (each ''value'' has a type) can be stored in any variable. Starting with [[ECMAScript#6th Edition – ECMAScript 2015|ES6]], the 6th version of the language, variables could be declared with <code>var</code> for function scoped variables, and <code>let</code> or <code>const</code> which are for [[block scope|block level]] variables. Before ES6, variables could only be declared with a <code>var</code> statement. Values assigned to variables declared with <code>const</code> cannot be changed, but its properties can. <code>var</code> should no longer be used since <code>let</code> and <code>const</code> are supported by modern browsers<ref>{{Cite web |date=2023-05-09 |title=Storing the information you need — Variables - Learn web development {{!}} MDN |url=https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Variables |access-date=2023-06-23 |website=developer.mozilla.org |language=en-US}}</ref>. A variable's [[Identifier (computer languages)|identifier]] must start with a letter, underscore (<code>_</code>), or dollar sign (<code>$</code>), while subsequent characters can also be digits (<code>0-9</code>). JavaScript is case sensitive, so the uppercase characters "A" through "Z" are different from the lowercase characters "a" through "z".
 
Starting with JavaScript 1.5, [[ISO 8859-1]] or [[Unicode]] letters (or <code>\uXXXX</code> Unicode escape sequences) can be used in identifiers.<ref>{{cite web | url=https://developer.mozilla.org/en/JavaScript/Guide/Values,_Variables,_and_Literals&revision=22#Variables | title=Values, Variables, and Literals - MDC | date=16 September 2010 | publisher=Mozilla Developer Network | access-date=1 February 2020 | archive-url=https://web.archive.org/web/20110629131728/https://developer.mozilla.org/en/JavaScript/Guide/Values%2C_Variables%2C_and_Literals%26revision%3D22#Variables | archive-date=29 June 2011 | url-status=dead }}</ref> In certain JavaScript implementations, the at sign (@) can be used in an identifier, but this is contrary to the specifications and not supported in newer implementations. {{Citation needed|date=January 2021}}
Line 182:
 
<syntaxhighlight lang="javascript">
varlet test; // variable declared, but not defined, ...
// ... set to value of undefined
varconst testObj = {};
console.log(test); // test variable exists, but value not ...
// ... defined, displays undefined
Line 198:
 
<syntaxhighlight lang="javascript">
function isUndefined(x) { varlet u; return x === u; } // like this...
function isUndefined(x) { return x === void 0; } // ... or that second one
function isUndefined(x) { return (typeof x) === "undefined"; } // ... or that third one
Line 271:
 
<syntaxhighlight lang="javascript">
varconst myString = "123.456";
varconst myNumber1 = Number(myString);
varconst myNumber2 = +myString;
</syntaxhighlight>
 
Line 279:
 
<syntaxhighlight lang="javascript">
const myNumericWrapper = new Number(123.456);
</syntaxhighlight>
 
Line 307:
 
<syntaxhighlight lang="javascript">
varconst greeting = "Hello, World!";
varconst anotherGreeting = 'Greetings, people of Earth.';
</syntaxhighlight>
 
Line 314:
 
<syntaxhighlight lang="javascript">
varconst h = greeting.charAt(0);
</syntaxhighlight>
 
Line 320:
 
<syntaxhighlight lang="javascript">
varconst h = greeting[0];
</syntaxhighlight>
 
Line 332:
 
<syntaxhighlight lang="javascript">
varconst x = "World";
varconst compare1 = ("Hello, " + x == "Hello, World"); // Here compare1 contains true.
varconst compare2 = ("Hello, " + x == "hello, World"); // Here compare2 contains ...
// ... false since the ...
// ... first characters ...
// ... of both operands ...
// ... are not of the same case.
</syntaxhighlight>
 
Line 344:
 
<syntaxhighlight lang="javascript">
varlet x = '"Hello, World!" he said.'; // Just fine.
var x = ""Hello, World!" he said."; // Not good.
var x = "\"Hello, World!\" he said."; // Works by escaping " with \"
</syntaxhighlight>
 
Line 352:
 
<syntaxhighlight lang="javascript">
varconst greeting = new String("Hello, World!");
</syntaxhighlight>
 
Line 358:
 
<syntaxhighlight lang="javascript">
varconst s = new String("Hello !");
typeof s; // Is 'object'.
typeof s.valueOf(); // Is 'string'.
Line 366:
 
<syntaxhighlight lang="javascript">
varconst s1 = new String("Hello !");
varconst s2 = new String("Hello !");
s1 == s2; // Is false, because they are two distinct objects.
s1.valueOf() == s2.valueOf(); // Is true.
Line 416:
 
<syntaxhighlight lang="javascript">
varconst b = new Boolean(false); // Object false {}
varconst t = Boolean(b); // Boolean true
varconst f = Boolean(b.valueOf()); // Boolean false
varlet n = new Boolean(b); // Not recommended
n = new Boolean(b.valueOf()); // Preferred
 
Line 435:
 
<syntaxhighlight lang="javascript">
varlet x = Symbol(1);
varconst y = Symbol(1);
x === y; // => false
 
varconst symbolObject = {};
varconst normalObject = {};
 
// since x and y are unique,
Line 470:
 
<syntaxhighlight lang="javascript">
letconst x = [1, 2, 3, 4]; // x is an Array
x[Symbol.iterator] === Array.prototype[Symbol.iterator]; // and Arrays are iterable
 
Line 504:
 
<syntaxhighlight lang="javascript">
varconst myArray = []; // Point the variable myArray to a newly ...
// ... created, empty Array
myArray.push("hello World"); // Fill the next empty index, in this case 0
console.log(myArray[0]); // Equivalent to console.log("hello World");
</syntaxhighlight>
 
Line 550:
 
<syntaxhighlight lang="javascript">
const dog = {color: "brown", size: "large"};
dog["color"]; // results in "brown"
dog.color; // also results in "brown"
Line 558:
 
<syntaxhighlight lang="javascript">
const cats = [{color: "brown", size: "large"},
{color: "black", size: "small"}];
cats[0]["size"]; // results in "large"
 
const dogs = {rover: {color: "brown", size: "large"},
spot: {color: "black", size: "small"}};
dogs["spot"]["size"]; // results in "small"
Line 582:
 
<syntaxhighlight lang="javascript">
varconst d = new Date(2010, 2, 1, 14, 25, 30); // 2010-Mar-01 14:25:30;
 
// Displays '2010-3-1 14:25:30':
Line 776:
====Capturing groups====
<syntaxhighlight lang="javascript">
varconst myRe = /(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})/;
varconst results = myRe.exec("The date and time are 2009-09-08 09:37:08.");
if (results) {
console.log("Matched: " + results[0]); // Entire match
varconst my_date = results[1]; // First group == "2009-09-08"
varconst my_time = results[2]; // Second group == "09:37:08"
console.log("`It is " + ${my_time + "} on " + ${my_date}`);
} else console.log("Did not find a valid date!");
</syntaxhighlight>
Line 791:
<syntaxhighlight lang="javascript">
// x, y is the argument. 'return x + y' is the function body, which is the last in the argument list.
varconst add = new Function('x', 'y', 'return x + y');
add(1, 2); // => 3
</syntaxhighlight>
Line 798:
 
<syntaxhighlight lang="javascript">
varconst add = function(x, y) {
return x + y;
};
Line 807:
 
<syntaxhighlight lang="javascript">
varconst add = (x, y) => {return x + y;};
// values can also be implicitly returned (i.e. no return statement is needed)
varconst addImplicit = (x, y) => x + y;
 
add(1, 2); // => 3
Line 912:
 
<syntaxhighlight lang="javascript">
varlet x = 1;
console.log(++x); // x becomes 2; displays 2
console.log(x++); // displays 2; x becomes 3
Line 924:
 
<syntaxhighlight lang="javascript">
varconst x = 17;
console.log(x%5); // displays 2
console.log(x%6); // displays 5
Line 935:
 
<syntaxhighlight lang="javascript">
varconst x = 17;
console.log((-x%5+5)%5); // displays 3
</syntaxhighlight>
You could also do:
<syntaxhighlight lang="javascript">
varconst x = 17;
console.log(Math.abs(-x%5)); // also 3
</syntaxhighlight>
Line 965:
 
<syntaxhighlight lang="javascript">
varlet x = 9;
x += 1;
console.log(x); // displays: 10
Line 984:
* To learn JavaScript objects...
*/
varconst object_1 = {a: 1}; // assign reference of newly created object to object_1
varlet object_2 = {a: 0};
varlet object_3 = object_2; // object_3 references the same object as object_2 does
object_3.a = 2;
Line 1,017:
 
<syntaxhighlight lang="javascript">
varlet a, b, c, d, e;
[a, b, c] = [3, 4, 5];
console.log(`${a + '},' + ${b + '},' + ${c}`); // displays: 3,4,5
e = {foo: 5, bar: 6, baz: ['Baz', 'Content']};
varconst arr = [];
({baz: [arr[0], arr[3]], foo: a, bar: b}) = e;
console.log(`${a + '},' + ${b + '},' + ${arr}`); // displays: 5,6,Baz,,,Content
[a, b] = [b, a]; // swap contents of a and b
console.log(a + ',' + b); // displays: 6,5
Line 1,029:
[a, b, c] = [3, 4, 5]; // permutations
[a, b, c] = [b, c, a];
console.log(`${a + '},' + ${b + '},' + ${c}`); // displays: 4,5,3
</syntaxhighlight>
 
Line 1,041:
 
<syntaxhighlight lang="javascript" line="1">
varconst a = [1, 2, 3, 4];
 
// It can be used multiple times in the same expression
varconst b = [...a, ...a]; // b = [1, 2, 3, 4, 1, 2, 3, 4];
 
// It can be combined with non-spread items.
varconst c = [5, 6, ...a, 7, 9]; // c = [5, 6, 1, 2, 3, 4, 7, 9];
 
// For comparison, doing this without the spread operator
// creates a nested array.
varconst d = [a, a]; // d = [[1, 2, 3, 4], [1, 2, 3, 4]]
 
// It works the same with function calls
function foo(arg1, arg2, arg3) {
console.log(`${arg1 + '}:' + ${arg2 + '}:' + ${arg3}`);
}
 
Line 1,107:
 
<syntaxhighlight lang="javascript">
varconst obj1 = {a: 1};
varconst obj2 = {a: 1};
varconst obj3 = obj1;
console.log(obj1 == obj2); //false
console.log(obj3 == obj1); //true
Line 1,200:
 
<syntaxhighlight lang="javascript">
varconst s = t || "(default)"; // assigns t, or the default value, if t is null, empty, etc.
</syntaxhighlight>
 
Line 1,241:
 
<syntaxhighlight lang="javascript">
const x = 11 & 6;
console.log(x); // 2
</syntaxhighlight>
Line 1,274:
 
<syntaxhighlight lang="javascript">
let x=7;
console.log(x); // 7
x<<=3;
Line 1,294:
 
<syntaxhighlight lang="javascript">
let str = "ab" + "cd"; // "abcd"
str += "e"; // "abcde"
 
const str2 = "2" + 2; // "22", not "4" or 4.
</syntaxhighlight>
 
Line 1,325:
 
<syntaxhighlight lang="javascript">
const result = condition ? expression : alternative;
</syntaxhighlight>
 
Line 1,331:
 
<syntaxhighlight lang="javascript">
if (condition) {
const result = expression;
} else {
const result = alternative;
}
</syntaxhighlight>
 
Line 1,431:
<syntaxhighlight lang="javascript">
with (document) {
varconst a = getElementById('a');
varconst b = getElementById('b');
varconst c = getElementById('c');
};
</syntaxhighlight>
Line 1,446:
 
<syntaxhighlight lang="javascript">
loop1: for (varlet a = 0; a < 10; ++a) {
if (a === 4) break loop1; // Stops after the 4th attempt
console.log('a = ' + a);
loop2: for (varlet b = 0; b < 10; ++b) {
if (b === 3) continue loop2; // Number 3 is skipped
if (b === 6) continue loop1; // Continues the first loop, 'finished' is not shown
Line 1,503:
 
<syntaxhighlight lang="javascript">
varconst obj1 = {a : 1};
varconst obj2 = {b : 2};
function foo(p) {
p = obj2; // Ignores actual parameter
Line 1,510:
}
foo(obj1, 3); // Does not affect obj1 at all. 3 is additional parameter
console.log(`${obj1.a} + " " + ${obj2.b}`); // writes 1 3
</syntaxhighlight>
 
Line 1,542:
<syntaxhighlight lang="javascript">
// Constructor
varconst anObject = new Object();
 
// Object literal
varconst objectA = {};
varconst objectA2 = {}; // A != A2, {}s create new objects as copies.
varconst objectB = {index1: 'value 1', index2: 'value 2'};
 
// Custom constructor (see below)
Line 1,555:
 
<syntaxhighlight lang="javascript">
varconst myStructure = {
name: {
first: "Mel",
Line 1,590:
}
 
varconst foo1 = new Foo(1);
varconst foo2 = new Foo(0);
foo2.prefix = "b-";
 
Line 1,598:
 
foo1.m3 = px; // Assigns the function itself, not its evaluated result, i.e. not px()
varconst baz = {"prefix": "c-"};
baz.m4 = px; // No need for a constructor to make an object.
 
Line 1,622:
console.log(MyObject.staticC); // blue
 
const object = new MyObject('red', 1000);
 
console.log(object.attributeA); // red
console.log(object[".attributeB"]); // 1000
 
console.log(object.staticC); // undefined
Line 1,642:
// x = new Foo() would set x's prototype to Foo.prototype,
// and Foo.prototype has a constructor slot pointing back to Foo).
const x = new Foo();
// The above is almost equivalent to
const y = {};
y.constructor = Foo;
y.constructor();
// Except
x.constructor == y.constructor; // true
x instanceof Foo; // true
y instanceof Foo; // false
// y's prototype is Object.prototype, not
// Foo.prototype, since it was initialised with
Line 1,684:
}
 
const base = new Base();
Derived.prototype = base; // Must be before new Derived()
Derived.prototype.constructor = Derived; // Required to make `instanceof` work
 
const d = new Derived(); // Copies Derived.prototype to d instance's hidden prototype slot.
d instanceof Derived; // true
d instanceof Base; // true
 
base.aBaseFunction = function() { console.log("Base::aNEWBaseFunction()"); };
 
d.anOverride(); // Derived::anOverride()
Line 1,711:
 
Base.prototype.m = m2;
const bar = new Base();
console.log("bar.m " + bar.m()); // bar.m Two
 
function Top() { this.m = m3; }
const t = new Top();
 
const foo = new Base();
Base.prototype = t;
// No effect on foo, the *reference* to t is copied.
console.log("foo.m " + foo.m()); // foo.m Two
 
const baz = new Base();
console.log("baz.m " + baz.m()); // baz.m Three