Javascript Slide2
Javascript Slide2
Operators
1
Expressions
• An expression is a phrase of JavaScript that can be evaluated
to produce a value.
• Primary Expressions : Primary expressions in JavaScript are
constant or literal values, certain language keywords, and
variable references.
1.23 // A number literal
"hello" // A string literal
/pattern/ // A regular expression literal
null // Evaluates to the null value
this // Evaluates to the "current" object
i // Evaluates to the value of the variable i.
sum // Evaluates to the value of the variable sum.
2
Expressions
• Object and Array Initializers : Object and array initializers are
expressions whose value is a newly created object or array.
These initializer expressions are sometimes called object
literals and array literals. Unlike true literals, however, they are
not primary expressions, because they include a number of
subexpressions that specify property and element values.
• An array initializer is a comma-separated list of expressions
contained within square brackets.
let a = [] // An empty array
let a = [1,2,3,4] // A 4-element array.
• Object initializer expressions are like array initializer
expressions, but the square brackets are replaced by curly
brackets, and each sub expression is prefixed with a property
name and a colon.
let p = { x: 2.3, y: -1.2 }; // An object with 2 properties 3
Expressions
• Function Definition Expressions : A function definition expression defines
a JavaScript function, and the value of such an expression is the newly
defined function. In a sense, a function definition expression is a “function
literal” in the same way that an object initializer is an “object literal.”
let square = function(x) { return x * x; };
• Property Access Expression : A property access expression evaluates to
the value of an object property or an array element. JavaScript defines
two syntaxes for property access:
expression . Identifier // syntax 1
expression [ expression ] // syntax 2
let o = {x: 1, y: {z: 3}}; // An example object
let a = [o, 4, [5, 6]]; // An example array that contains the object
o.x // => 1: property x of expression o
o.y.z // => 3: property z of expression o.y
o["x"] // => 1: property x of object o
a[1] // => 4: element at index 1 of expression a
4
Expressions
• Conditional Property Access : ES2020 adds two new kinds of
property access expressions.
expression ?. Identifier // format 1
expression ?.[ expression ] //format2
In a regular property access expression using . or [], you get a
TypeError if the expression on the left evaluates to null or
undefined. You can use ?. and ?.[] syntax to guard against errors
of this type.
let a = { b: null };
a.b?.c.d // => undefined
-----------------------------------
let a;
let index = 0;
a?.[index++] // => undefined: because a is undefined
5
Expressions
• Invocation Expressions : An invocation expression is JavaScript’s
syntax for calling (or executing) a function or method.
f(0) // f is the function expression; 0 is the argument
expression.
Math.max(x,y,z) // Math.max is the function; x, y, and z are
the arguments.
8
Operator
• Number of Operands : Operators can be categorized based on
the number of operands they expect (their arity). JavaScript
supports unary(− operator), binary(* multiplication operator)
and ternary operator(conditional operator ?:).
• Operand and Result Type : Some operators work on values of
any type, but most expect their operands to be of a specific type,
and most operators return (or evaluate to) a value of a specific
type.
• Operator Precedence : The operators listed in previous table are
arranged in order from high precedence to low precedence.
• Operator Associativity : The associativity of an operator
specifies the order in which operations of the same precedence
are performed. Left-to-right associativity means that operations
are performed from left to right
9
Arithmetic Expressions
• The basic arithmetic operators are ** (exponentiation),
*(multiplication), / (division), % (modulo: remainder after
division), + (addition), and - (subtraction).
• The + Operator : The binary + operator adds numeric
operands or concatenates string operands.
13
Logical Expressions
• Logical OR (||) : The || operator performs the Boolean OR
operation on its two operands. If one or both operands is
truthy, it returns a truthy value. If both operands are falsy, it
returns a falsy value.
let max = maxWidth || preferences.maxWidth || 500;
15
Evaluation Expressions
• JavaScript has the ability to interpret strings of JavaScript
source code, evaluating them to produce a value.
JavaScript does this with the global function eval():
eval("3+2") // => 5
16
Evaluation Expressions
Global eval() :
const geval = eval; // Using another name does a global eval
let x = "global", y = "global"; // Two global variables
function f() { // This function does a local eval
let x = "local"; // Define a local variable
eval("x += 'changed';"); // Direct eval sets local variable
return x; // Return changed local variable
}
function g() { // This function does a global eval
let y = "local"; // A local variable
geval("y += 'changed';"); // Indirect eval sets global variable
return y; // Return unchanged local variable
}
console.log(f(), x); // Local variable changed: prints "localchanged global":
console.log(g(), y); // Global variable changed: prints "local
globalchanged":
17
Miscellaneous Operators
• The Conditional Operator (?:) : The conditional operator is the
only ternary operator (three operands) in JavaScript and is
sometimes actually called the ternary operator. This operator
has three operands, the first goes before the ?, the second
goes between the ? and the :, and the third goes after the :.
x > 0 ? x : -x // The absolute value of x
• First-Defined (??) : The first-defined operator ?? evaluates to
its first defined operand: if its left operand is not null and not
undefined, it returns that value. Otherwise, it returns the
value of the right operand. Like the && and || operators, ?? is
short-circuiting: it only evaluates its second operand if the first
operand evaluates to null or undefined. If the expression
a has no side effects, then the expression a ?? b is equivalent
to:
(a !== null && a !== undefined) ? a : b 18
Miscellaneous Operators
• The typeof Operator : typeof is a unary operator that is placed before
its single operand, which can be of any type. Its value is a string that
specifies the type of the operand.
// If the value is a string, wrap it in quotes, otherwise,convert
(typeof value === "string") ? "'" + value + "'" : value.toString()
21
Expression Statements
• The simplest kinds of statements in JavaScript are expressions
that have side effects.
• Example :
greeting = "Hello " + name;
i *= 3;
counter++;
• The delete operator has the important side effect of deleting an
object property.
delete o.x;
• Function calls are another major category of expression
statements. For example:
console.log(debugMessage);
displaySpinner(); // A hypothetical function to display a
spinner in a web app.
22
Compound and Empty Statements
• A statement block combines multiple statements into a single
compound statement. A statement block is simply a sequence
of statements enclosed within curly braces.
• Example :
{
x = Math.PI;
cx = Math.cos(x);
console.log("cos(π) = " + cx);
}
• The JavaScript interpreter takes no action when it executes an
empty statement. The empty statement is occasionally useful
when you want to create a loop that has an empty body.
// Initialize an array a
for(let i = 0; i < a.length; a[i++] = 0) ; 23
Conditionals Statements
• if : The if statement is the fundamental control statement that
allows JavaScript to make decisions, or, more precisely, to
execute statements conditionally. This statement has two
forms.
if (expression)
statement
and
if (expression)
statement1
else
statement2
• Example :
if (n === 1) console.log("You have 1 new message.");
else console.log(`You have ${n} new messages.`); 24
Conditionals Statements
• else if :
if (n === 1) {
// Execute code block #1
} else if (n === 2) {
// Execute code block #2
} else if (n === 3) {
// Execute code block #3
} else {
// If all else fails, execute block #4
}
25
Conditionals Statements
• switch :
switch(n) {
case 1: // Start here if n === 1
// Execute code block #1.
break; // Stop here
case 2: // Start here if n === 2
// Execute code block #2.
break; // Stop here
case 3: // Start here if n === 3
// Execute code block #3.
break; // Stop here
default: // If all else fails...
// Execute code block #4.
break; // Stop here
} 26
Loops
• JavaScript has five looping statements: while, do/while, for,
for/of and for/in.
• while :
while (expression)
statement
• do/while :
do
statement
while (expression);
• for :
for(initialize ; test ; increment)
statement
27
Loops
• ES6 defines a new loop statement: for/of:
The for/of loop works with iterable objects. Arrays, strings, sets, and maps
are iterable: they represent a sequence or set of elements that you can
loop or iterate through using a for/of loop.
let data = [1, 2, 3, 4, 5, 6, 7, 8, 9], sum = 0;
for(let element of data) {
sum += element;
}
sum // => 45
• FOR/OF WITH OBJECTS
Objects are not (by default) iterable. If you want to iterate through the
properties of an object, you can use the for/in loop or use for/of with the
Object.keys() method:
let o = { x: 1, y: 2, z: 3 }; let keys = "";
for(let k of Object.keys(o)) {
keys += k; } keys // => "xyz"
28
Loops
• for/in : for/in loop works with any object after the in. The
for/of loop is new in ES6, but for/in has been part of
JavaScript since the very beginning.
Syntax :
for (variable in object)
statement
Example:
for(let p in o) { // Assign property names of o to variable p
console.log(o[p]); // Print the value of each property
}
29
Jumps
• Another category of JavaScript statements are jump
statements. As the name implies, these cause the JavaScript
interpreter to jump to a new location in the source code.
• Labeled Statements : Any statement may be labeled by preceding it with an
identifier and a colon:
identifier: statement
• break : The break statement, used alone, causes the innermost enclosing
loop or switch statement to exit immediately.
break;
• continue : The continue statement is similar to the break statement.
Instead of exiting a loop, however, continue restarts a loop at the next
iteration.
continue;
• return : Function invocations are expressions and all expressions have
values. A return statement within a function specifies the value of
invocations of that function.
return expression; 30
Jumps
• yield : The yield statement is much like the return statement
but is used only in ES6 generator functions to produce the
next value in the generated sequence of values without
actually returning.
function* range(from, to) {
for(let i = from; i <= to; i++) {
yield i;
}
}
• throw : An exception is a signal that indicates that some sort
of exceptional condition or error has occurred. To throw an
exception is to signal such an error or exceptional condition.
throw expression;
31
Jumps
• Example yield :
• function* countAppleSales() {
• const saleList = [3, 7, 5];
• for (const sale of saleList) {
• yield sale;
• }
• }
• -----------------
• const appleStore = countAppleSales(); // Generator { }
• console.log(appleStore.next()); // { value: 3, done: false }
• console.log(appleStore.next()); // { value: 7, done: false }
• console.log(appleStore.next()); // { value: 5, done: false }
• console.log(appleStore.next()); // { value: undefined, done:
true } 32
Jumps
Example throw:
function getRectArea(width, height)
{ if (isNaN(width) || isNaN(height))
{ throw new Error("Parameter is not a number!");
}
}
33
Jumps
• try/catch/finally :
The try/catch/finally statement is JavaScript’s exception
handling mechanism. The try clause of this statement simply
defines the block of code whose exceptions are to be handled.
The try block is followed by a catch clause, which is a block of
statements that are invoked when an exception occurs
anywhere within the try block. The catch clause is followed by
a finally block containing cleanup code that is guaranteed to
be executed, regardless of what happens in the try block.
try { }
catch(e) { }
finally {}
34
Jumps
• Example finally :
try {
// Code that might throw an error
let result = 10 / 0; // This will cause an error
console.log(result);
} catch (error) {
console.error("An error occurred:", error.message);
}
finally {
console.log("This code in 'finally' block always executes.");
// Resource cleanup or finalization
}
35
Miscellaneous Statements
• with : The with statement runs a block of code as if the
properties of a specified object were variables in scope for that
code.
with (object)
statement
• debugger : This statement acts like a breakpoint: execution of
JavaScript code stops, and you can use the debugger to print
variables’ values, examine the call stack, and so on.
if (o === undefined) debugger; // Temporary line for
debugging purposes
• “use strict” : "use strict" is a directive introduced in ES5.
Directives are not statements. The purpose of a "use strict"
directive is to indicate that the code that follows (in the script or
function) is strict code.
36
Miscellaneous Statements
• Example with :
const person = {
name: 'Alice', age: 30
};
with (person) {
console.log(name); // Outputs: Alice
console.log(age); // Outputs: 30
}
37
Miscellaneous Statements
Example use strict :
Globally: Place "use strict"; as the very first statement in a
JavaScript file to enable strict mode for the entire script.
---------------
"use strict"; // All code in this file runs in strict mode
let x = 10; // ...
--------------
Locally (within a function): Place "use strict"; as the very first
statement inside a function to enable strict mode only for that
specific function and any nested functions within it.
--------------------------------
function myStrictFunction() {
"use strict"; // Code inside this function runs in strict mode
let y = 20;
} // Code outside this function runs in non-strict mode 38
Miscellaneous Statements
• Non-Strict Mode (Sloppy Mode):
• This is the default mode for JavaScript code if 'use strict'; is
not explicitly declared.
• It is more forgiving of certain syntax errors and potentially
problematic behaviors, such as:
– Implicitly creating global variables by assigning a value to an
undeclared variable.
– Allowing duplicate parameter names in function declarations.
– Silently failing when attempting to assign a value to a read-only
property.
– Allowing the with statement, which can make code harder to
optimize.
– The this keyword in a function called without an explicit object
context defaults to the global object (e.g., window in browsers).
39
Miscellaneous Statements
• Strict Mode:
• Enabled by adding the directive 'use strict'; at the beginning of a script or a
function.
• It introduces stricter parsing and error handling, making the code more robust
and secure.
• Key changes in strict mode include:
– Eliminating silent errors: Errors that would fail silently in non-strict mode now throw
exceptions (e.g., assigning to an undeclared variable throws a ReferenceError).
– Disallowing certain syntax: Forbids features that are considered problematic or
potentially confusing (e.g., the with statement, octal literals without the 0o prefix,
duplicate parameter names).
– Changing this behavior: In functions called without an explicit
object, this is undefined instead of the global object. This prevents accidental global
variable creation.
– Stricter eval and arguments semantics: Reduces the potential for runtime errors and
improves performance.
– Preventing deletion of non-deletable properties: Throws an error when attempting
to delete variables, functions, or arguments, or non-configurable properties.
40
Declarations
• JavaScript declarations are used to define constants, variables,
functions, and classes and for importing and exporting values between
modules.
• const, let, and var : In ES6 and later, const declares constants, and let declares
variables. Prior to ES6, the var keyword was the only way to declare variables
and there was no way to declare constants.
• function : The function declaration is used to define functions.
• class : In ES6 and later, the class declaration creates a new class and gives it a
name that we can use to refer to it.
• import and export : The only way that a value (such as function or class)
defined in one module can be used in another module is if the defining module
exports it with export and the using module imports it with import.
// geometry/constants.js
const PI = Math.PI;
const TAU = 2 * PI;
export { PI, TAU };
42
Import
43
Import
44
Import
45
Export
46
Export
47