KEMBAR78
Javascript Slide2 | PDF | Control Flow | Boolean Algebra
0% found this document useful (0 votes)
3 views47 pages

Javascript Slide2

Uploaded by

dev
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views47 pages

Javascript Slide2

Uploaded by

dev
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

Expressions and

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.

• Conditional Invocation : Normally when you invoke a function, if


the expression to the left of the parentheses is null or undefined or
any other non-function, a TypeError is thrown. With the new ?.()
invocation syntax, if the expression to the left of the ?. evaluates to
null or undefined, then the entire invocation expression evaluates
to undefined and no exception is thrown.
let f = null, x = 0;
f?.(x++) // => undefined: f is null, but no exception thrown
6
Expressions
• Object Creation Expressions : An object creation expression
creates a new object and invokes a function (called a
constructor) to initialize the properties of that object. Object
creation expressions are like invocation expressions except
that they are prefixed with the keyword new.
new Object()
new Point(2,3)
If no arguments are passed to the constructor function in an
object creation expression, the empty pair of parentheses can
be omitted.
new Object
new Date
The value of an object creation expression is the newly
created object.
7
JavaScript Operator
• Operators are used for JavaScript’s arithmetic expressions,
comparison expressions, logical expressions, assignment
expressions, and more.
Operator Operation A(associa N( No of Types
tivity) operands)
++ Pre- or post- R(right-to- 1 lval→num
increment left)
delete Remove a R 1 lval→bool
property
*, /, % Multiply, L(left-toright) 2 num,num→n
divide, um
remainder
+ Concatenate L 2 str,str→str
strings
=== Test for strict L 2 any,any→bo
equality ol

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.

• Unary Arithmetic Operators : Unary operators modify the


value of a single operand to produce a new value. In
JavaScript, the unary operators all have high precedence and
are all right-associative.

• Bitwise Operators : The bitwise operators perform low-level


manipulation of the bits in the binary representation of
numbers.
10
Relational Expressions
• These operators test for a relationship (such as “equals,” “less
than,” or “property of”) between two values and return true or
false depending on whether that relationship exists.
• Equality and Inequality Operators : The == and === operators
check whether two values are the same, using two different
definitions of sameness. Both operators accept operands of any
type, and both return true if their operands are the same and
false if they are different. The != and !== operators test for the
exact opposite of the == and === operators.
• Comparison Operators : The comparison operators test the
relative order (numerical or alphabetical) of their two
operands.
11 < 3 // => false: numeric comparison.
"11" < "3" // => true: string comparison.
"11" < 3 // => false: numeric comparison, "11" converted to 11.11
Relational Expressions
• The in Operator : The in operator expects a left-side operand that
is a string, symbol, or value that can be converted to a string. It
expects a right-side operand that is an object. It evaluates to true
if the left-side value is the name of a property of the right-side
object.
let point = {x: 1, y: 1}; // Define an object
"x" in point // => true: object has property named "x"
"z" in point // => false: object has no "z“ property.
• The instanceof Operator : The instanceof operator expects a left-
side operand that is an object and a right-side operand that
identifies a class of objects.
let d = new Date(); // Create a new object with the Date()
constructor
d instanceof Date // => true: d was created with Date()
d instanceof Object // => true: all objects are instances of Object 12
Logical Expressions
• The logical operators &&, ||, and ! perform Boolean algebra
and are often used in conjunction with the relational
operators to combine two relational expressions into one
more complex expression.
• Logical AND (&&) : The && operator can be understood at
three different levels. At the simplest level, when used with
boolean operands, && performs the Boolean AND operation
on the two values: it returns true if and only if both its first
operand and its second operand are true. If one or both of
these operands is false, it returns false.
&& is often used as a conjunction to join two relational
expressions:
x === 0 && y === 0 // true if, and only if, x and y are both 0

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;

• Logical NOT (!) : The ! operator is a unary operator; it is placed


before a single operand. Its purpose is to invert the boolean
value of its operand. For example, if x is truthy, !x evaluates to
false. If x is falsy, then !x is true.
• Unlike the && and || operators, the ! operator converts its
operand to a boolean value before inverting the converted
value. This means that ! always returns true or false and that
you can convert any value x to its equivalent boolean value by
applying this operator twice: !!x.
14
Assignment Expressions
• JavaScript uses the = operator to assign a value to a variable
or property. The = operator expects its left-side operand to be
an lvalue: a variable or object property (or array element).
i = 0; // Set the variable i to 0.
o.x = 1; // Set the property x of object o to 1.
• Assignment with Operation : JavaScript supports a number of
other assignment operators that provide shortcuts by
combining assignment with some other operation. For
example, the += operator performs addition and assignment.
Operator Example Equivalent
+= a += b a=a+b
&= a &= b a=a&b

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

• eval() : eval() expects one argument. If you pass any value


other than a string, it simply returns that value. If you pass a
string, it attempts to parse the string as JavaScript code,
throwing a SyntaxError if it fails. If it successfully parses the
string, then it evaluates the code and returns the value of the
last expression or statement in the string or undefined if the
last expression or statement had no value.

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()

• The delete Operator : delete is a unary operator that attempts to delete


the object property or array element specified as its operand.
let o = { x: 1, y: 2}; // Start with an object
delete o.x; // Delete one of its properties
"x" in o // => false: the property does not exist anymore

let a = [1,2,3]; // Start with an array


delete a[2]; // Delete the last element of the array
2 in a // => false: array element 2 doesn't exist anymore
a.length // => 3: note that array length doesn't change, though 19
Miscellaneous Operators
• The void Operator : void is a unary operator that appears
before its single operand, which may be of any type. This
operator is unusual and infrequently used; it evaluates its
operand, then discards the value and returns undefined.
Since the operand value is discarded, using the void operator
makes sense only if the operand has side effects.
• The comma Operator (,) : The comma operator is a binary
operator whose operands may be of any type. It evaluates its
left operand, evaluates its right operand, and then returns the
value of the right operand. The only situation in which the
comma operator is commonly used is with a for loop that has
multiple loop variables:
for(let i=0,j=10; i < j; i++,j--) {
console.log(i+j);}
20
Statements

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!");
}
}

try { getRectArea(3, "A");}


catch (e)
{ console.error(e);
// Expected output: 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 };

import { PI, TAU } from './geometry/constants.js'; 41


Import

42
Import

43
Import

44
Import

45
Export

46
Export

47

You might also like