π Lecture 69 β Array Methods
π Overview: This lecture provides a comprehensive exploration of JavaScript array methods, including operations for converting, modifying, sorting, and manipulating arrays. It also covers comparisons, conditions, loops, error handling, and debugging techniques essential for effective JavaScript programming.
ποΈ Topics Covered
The lecture covers JavaScript array methods such as converting arrays to strings, popping and pushing elements, shifting, changing, deleting, splicing, sorting, reversing, using the compare function, joining, and slicing arrays. It then moves into JavaScript comparisons including comparison operators, logical operators, conditional operators, comparing different types, and bitwise operators. Following that, JavaScript conditions are explained with if, else, and else if statements. The switch statement, for loops, while loops, break and continue statements, data types, type conversion, regular expressions, hoisting, error handling with try/catch/throw/finally, and debugging methods are all covered in detail.
π Lecture Summary
Converting Arrays to Strings
In JavaScript, all objects have the valueOf() and toString() methods. The valueOf() method is the default behavior for an array and returns the array as a comma-separated string.
π Definition β valueOf(): The default method for arrays that returns the array elements as a comma-separated string.
π Example: var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.valueOf(); outputs Banana,Orange,Apple,Mango
Popping and Pushing
The pop() method removes the last element from an array. The push() method adds a new element to an array at the end.
π Definition β pop(): Removes the last element from an array.
π Example: var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.pop(); removes "Mango" from fruits.
π Definition β push(): Adds a new element to the end of an array.
π Example: var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.push("Kiwi"); adds "Kiwi" to the end of fruits.
Shifting Elements
The shift() method removes the first element of an array and shifts all other elements one position up.
π Definition β shift(): Removes the first element of an array and shifts remaining elements up.
π Example: var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.shift(); removes "Banana" from fruits.
Changing Elements
Array elements are accessed using their index number. Elements can be changed by assigning a new value to a specific index. You can also append a new element using the length property.
π Example: var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[0] = "Kiwi"; changes first element to "Kiwi". fruits[fruits.length] = "Kiwi"; appends "Kiwi" to the array.
Deleting Elements
Elements can be deleted using the JavaScript delete operator, which sets the element to undefined.
π Definition β delete operator: Removes an array element but leaves an undefined hole in the array.
π Example: var fruits = ["Banana", "Orange", "Apple", "Mango"]; delete fruits[0]; makes first element undefined: [undefined, "Orange", "Apple", "Mango"]
Splicing an Array
The splice() method can add new items to an array at a specified position, optionally removing elements.
π Definition β splice(): Adds/removes elements from an array. Parameters are: (position, how many elements to remove, new elements to add).
π Example: var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(2, 1, "Lemon", "Kiwi"); removes 1 element at index 2 and adds "Lemon" and "Kiwi", resulting in ["Banana", "Orange", "Lemon", "Kiwi", "Mango"]
π‘ Why this matters: The first parameter (2) defines position, second (1) defines how many to remove, rest define new elements.
Sorting an Array
The sort() method sorts an array alphabetically.
π Definition β sort(): Sorts array elements alphabetically.
π Example: var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort(); results in ["Apple", "Banana", "Mango", "Orange"]
Reversing an Array
The reverse() method reverses the elements in an array and can be used with sort() for descending order.
π Definition β reverse(): Reverses the order of array elements.
π Example: After sorting, fruits.reverse(); gives ["Orange", "Mango", "Banana", "Apple"]
The Compare Function
The compare function defines an alternative sort order for numeric sorting. It should return a negative, zero, or positive value.
π Definition β compare function: A function that defines sort order. Returns negative (a before b), zero, or positive (b before a).
π Formula: function(a, b){return a-b} β sorts numbers in ascending order.
π Example: var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a-b}); sorts numbers numerically. When comparing 40 and 100, the function returns 40-100 = -60 (negative), so 40 is sorted lower than 100.
Joining Arrays
The concat() method creates a new array by concatenating two or more arrays.
π Definition β concat(): Creates a new array by joining two or more arrays.
π Example: var myGirls = ["Aisha", "Meryam"]; var myBoys = ["Bilal", "Umer", "Ali"]; var myChildren = myGirls.concat(myBoys); results in ["Aisha", "Meryam", "Bilal", "Umer", "Ali"]
Slicing an Array
The slice() method extracts a portion of an array into a new array without modifying the original.
π Definition β slice(): Slices out a piece of an array into a new array. Parameters: (start index, end index β not included).
π Example: var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; var citrus = fruits.slice(1, 3); gives ["Orange", "Lemon"]. fruits.slice(2); gives ["Lemon", "Apple", "Mango"]
JavaScript Comparisons
Comparison operators are used to determine equality or difference between variables or values. Major operators include == (equal to), === (equal value and type), != (not equal), !== (not equal value or type), > (greater than), < (less than), >= (greater than or equal to), <= (less than or equal to).
π Example for x=5: x == 5 returns true, x === "5" returns false, x != 8 returns true, x > 8 returns false, x < 8 returns true, x >= 8 returns false.
Logical operators determine logic between variables: && (and), || (or), ! (not).
π For x=6, y=3: (x < 10 && y > 1) is true, (x == 5 || y == 5) is false, !(x == y) is true.
The conditional (ternary) operator assigns a value based on a condition.
π Formula: variablename = (condition) ? value1:value2
π Example: var vo = (age < 18) ? "Too young":"Old enough";
When comparing different types, JavaScript converts the number to a string for comparison. Comparing strings alphabetically means "2" is greater than "12" because 1 is less than 2. Variables should be converted to proper type before comparison using Number(age) and isNaN().
JavaScript Conditions
Conditional statements perform different actions for different decisions. The if statement executes code if a condition is true. The else statement executes code if the condition is false. The else if statement specifies a new condition if the first is false.
π Example: if (hour < 18) { greeting = "Good day"; } else { greeting = "Good evening"; }
π Example with else if: if (time < 10) { greeting = "Good morning"; } else if (time < 20) { greeting = "Good day"; } else { greeting = "Good evening"; }
JavaScript Switch Statement
The switch statement selects one of many blocks of code to execute based on different conditions.
π Formula:
switch(expression) {
case n1: code block; break;
case n2: code block; break;
default: default code block;
}
π Example: switch (new Date().getDay()) { case 0: day = "Sunday"; break; case 1: day = "Monday"; break; }
The break keyword stops execution and exits the switch block. The default keyword specifies code to run if no case matches. Multiple cases can share the same code block (fall-through).
JavaScript For Loop
Loops execute a block of code multiple times. The for loop loops through a block of code a number of times.
π Formula: for (statement 1; statement 2; statement 3) { code block }
- Statement 1 executes before the loop starts (initialization)
- Statement 2 defines the condition for running the loop
- Statement 3 executes each time after the loop
π Example: for (i = 0; i < 5; i++) { text += "The number is " + i; } outputs numbers 0 through 4.
All three statements are optional. Statement 1 can initialize multiple values. Statement 2 can be omitted but must have a break inside. Statement 3 can do negative increment or anything.
The for/in loop iterates through the properties of an object.
π Example: for (x in person) { text += person[x]; } outputs "John Doe 25"
JavaScript While Loop
The while loop executes a block of code as long as a specified condition is true.
π Formula: while (condition) { code block }
π Example: while (i < 10) { text += "The number is " + i; i++; }
The do/while loop executes the code block once before checking the condition, then repeats as long as the condition is true.
π Formula: do { code block } while (condition);
π Example: do { text += "The number is " + i; i++; } while (i < 10); always executes at least once.
A while loop is similar to a for loop with statement 1 and statement 3 omitted.
JavaScript Break and Continue
The break statement jumps out of a loop entirely. The continue statement jumps over one iteration and continues with the next.
π Example with break:
for (i = 0; i < 10; i++) {
if (i === 3) { break; }
text += "The number is " + i;
}
Output: numbers 0, 1, 2 (stops at 3).
π Example with continue:
for (i = 0; i < 10; i++) {
if (i === 3) { continue; }
text += "The number is " + i;
}
Output: numbers 0, 1, 2, 4, 5, 6, 7, 8, 9 (skips 3).
JavaScript Data Types
There are 5 data types that can contain values: String, Number, Boolean, Object, Function. There are 3 types of objects: Object, Date, Array. And 2 data types that cannot contain values: null, undefined.
The typeof operator finds the data type of a variable.
π Examples: typeof "John" returns "string", typeof 3.14 returns "number", typeof NaN returns "number", typeof [1,2,3,4] returns "object", typeof null returns "object".
The constructor property returns the constructor function for all JavaScript variables and can be used to check if an object is of a certain type.
JavaScript Type Conversion
JavaScript variables can be converted using JavaScript functions or automatically. The String() method converts numbers, booleans, and dates to strings. The toString() method does the same. Methods like toExponential(), toFixed(), and toPrecision() format numbers.
The Number() method converts strings to numbers (empty strings become 0, anything else becomes NaN). The unary + operator also converts variables to numbers.
Booleans convert to numbers: Number(false) returns 0, Number(true) returns 1. Dates convert to milliseconds.
Automatic type conversion happens when JavaScript operates on wrong data types: 5 + null returns 5, "5" + null returns "5null", "5" + 1 returns "51", "5" - 1 returns 4.
JavaScript RegExp
A regular expression is a sequence of characters forming a search pattern for text search and replace operations.
π Formula: /pattern/modifiers;
Modifiers include: i (case-insensitive), g (global match), m (multiline matching). Brackets find ranges: [abc] (any of characters), [0-9] (any digit), (x|y) (alternatives). Metacharacters include: \d (digit), \s (whitespace), \b (word boundary), \uxxxx (Unicode). Quantifiers include: n+ (one or more), n* (zero or more), n? (zero or one).
The test() method returns true/false if pattern is found. The exec() method returns the found text or null.
JavaScript Hoisting
Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope. Variables can be used before they are declared because declarations (not initializations) are hoisted.
π Example: x = 5; var x; works because var x; is hoisted to the top.
Only declarations are hoisted, not initializations. To avoid bugs, always declare all variables at the beginning of every scope.
JavaScript Error Handling
The try statement tests a block of code for errors. The catch statement handles the error. The throw statement creates custom errors. The finally statement executes code after try/catch regardless of result.
π Formula:
try { block of code to try }
catch(err) { block of code to handle errors }
finally { block of code executed regardless }
The throw statement allows custom exceptions: throw "Too big"; or throw 500;
π Input validation example:
try {
if (x == "") throw "empty";
if (isNaN(x)) throw "not a number";
if(x < 5) throw "too low";
if(x > 10) throw "too high";
} catch(err) {
message = "Input is " + err;
}
JavaScript Debugging
Debugging is searching for errors in programming code. All modern browsers have built-in debuggers. The console.log() method displays JavaScript values in the debugger window. Breakpoints stop code execution to examine values. The debugger keyword stops execution and calls the debugging function.
π Example: debugger; stops execution before the next line.
β Key Takeaways
Array methods like push(), pop(), shift(), splice(), slice(), sort(), reverse(), and concat() are essential for manipulating arrays efficiently. Comparison operators (==, ===, !=, !==, >, <, >=, <=) and logical operators (&&, ||, !) are fundamental for decision-making in conditional statements and loops. The for, while, and do/while loops enable repetitive code execution, with break and continue controlling loop flow. Understanding type conversion, regular expressions, hoisting (declarations moved to top), and error handling with try/catch/throw/finally is crucial for writing robust JavaScript code. Debugging tools like console.log() and the debugger keyword help identify and fix errors.
π§ Quick Revision Questions
- What does the splice() method do and what do its first two parameters represent?
- Explain the difference between == and === in JavaScript comparisons with an example.
- How does the ternary operator work? Provide its syntax and an example.
- What is the difference between break and continue statements in loops?
- What is hoisting in JavaScript and does it apply to initializations?
π Lecture 83 β JavaScript Best Practices
π Overview: This lecture covers essential JavaScript best practices for writing clean, efficient, and maintainable code. It emphasizes the importance of avoiding global variables, using proper declarations, and handling type conversions and comparisons correctly to prevent bugs and performance issues.
ποΈ Topics Covered
The lecture addresses several key best practices including avoiding global variables, always declaring local variables, placing declarations at the top, initializing variables, avoiding object declarations for primitives, using literal syntax instead of constructors, beingware of automatic type conversions, using strict equality (===), setting parameter defaults, and ending switch statements with defaults.
π Lecture Summary
Avoid Global Variables
Minimize the use of global variables, including all data types, objects, and functions. Global variables and functions can be overwritten by other scripts, causing unpredictable behavior. Use local variables instead, and learn how to use closures to maintain variable scope.
π‘ Why this matters: Global variables create dependencies and make code harder to maintain and debug, especially in larger projects with multiple scripts.
Always Declare Local Variables
All variables used in a function should be declared as local variables. Local variables must be declared with the var keyword; otherwise they will become global variables.
Declarations on Top
It is a good coding practice to put all declarations at the top of each script or function. This will:
- Give cleaner code
- Provide a single place to look for local variables
- Make it easier to avoid unwanted (implied) global variables
- Reduce the possibility of unwanted re-declarations
// Declare at the beginning
var firstName, lastName, price, discount, fullPrice;
// Use later
firstName = "John";
lastName = "Doe";
price = 19.90;
discount = 0.10;
fullPrice = price * 100 / discount;
This also goes for loop variables:
// Declare at the beginning
var i;
// Use later
for (i = 0; i < 5; i++) {
....
}
Initialize Variables
It is a good coding practice to initialize variables when you declare them. This will:
- Give cleaner code
- Provide a single place to initialize variables
- Avoid undefined values
Never Declare Number, String, or Boolean Objects
Always treat numbers, strings, or booleans as primitive values, not as objects. Declaring these types as objects slows down execution speed and produces nasty side effects.
var x = "John";
var y = new String("John");
(x === y) // is false because x is a string and y is an object.
Or even worse:
var x = new String("John");
var y = new String("John");
(x == y) // is false because you cannot compare objects.
Don't Use new Object()
- Use
{}instead ofnew Object() - Use
""instead ofnew String() - Use
0instead ofnew Number() - Use
falseinstead ofnew Boolean() - Use
[]instead ofnew Array() - Use
/()/instead ofnew RegExp() - Use
function(){}instead ofnew function()
Check this example:
var x1 = {}; // new object
var x2 = ""; // new primitive string
var x3 = 0; // new primitive number
var x4 = false; // new primitive boolean
var x5 = []; // new array object
var x6 = /()/; // new regexp object
var x7 = function(){}; // new function object
Beware of Automatic Type Conversions
Beware that numbers can accidentally be converted to strings or NaN (Not a Number). JavaScript is loosely typed. A variable can contain different data types, and a variable can change its data type.
var x = "Hello"; // typeof x is a string
x = 5; // changes typeof x to a number
When doing mathematical operations, JavaScript can convert numbers to strings. Subtracting a string from a string does not generate an error but returns NaN.
π Example:
"Hello" - "Dolly" // returns NaN
Use === Comparison
The == comparison operator always converts (to matching types) before comparison. The === operator forces comparison of values and type.
0 == ""; // true
1 == "1"; // true
1 == true; // true
0 === ""; // false
1 === "1"; // false
1 === true; // false
π Definition β Strict Equality (===): An operator that compares both values and types without performing type conversion.
Use Parameter Defaults
If a function is called with a missing argument, the value of the missing argument is set to undefined. Undefined values can break your code. It is a good habit to assign default values to arguments.
function myFunction(x, y) {
if (y === undefined) {
y = 0;
}
}
End Your Switches with Defaults
End your switch statements with defaults, even if you think it's not needed.
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
default:
day = "Unknown";
}
β Key Takeaways
The most critical practices from this lecture include: always declare variables at the top of their scope using var to avoid global scope pollution; initialize variables when declared to prevent undefined values; use primitive literals (e.g., "", 0, false, []) instead of constructor objects (new String(), new Number(), etc.) to avoid performance issues and unexpected behavior; always use === instead of == to avoid automatic type coercion; and be cautious of JavaScript's loose typing, which can cause numbers to become strings or NaN during operations.
π§ Quick Revision Questions
- Why should you avoid global variables in JavaScript?
- What is the difference between
==and===in JavaScript? - What does the expression
"Hello" - "Dolly"evaluate to in JavaScript, and why? - What is the recommended way to create an empty array:
new Array()or[]? Why? - What happens when a function is called with a missing argument in JavaScript?
π Lecture 85 β JavaScript Common Mistakes
π Overview: This lecture covers the most common mistakes programmers make in JavaScript and explains how to avoid them. Understanding these pitfalls is crucial for writing reliable, secure, and bug-free JavaScript code in real-world applications.
ποΈ Topics Covered
The lecture covers a comprehensive list of common JavaScript mistakes including: accidentally using assignment operator instead of comparison, expecting loose comparison versus strict comparison, switch statement issues with strict comparison, confusion between addition and concatenation, floating point precision problems, improper string breaking, semicolon misplacement, return statement breaking, array access with named indexes, array/object definition ending with commas, undefined versus null confusion, and block level scope expectations.
π Lecture Summary
Accidentally Using the Assignment Operator
JavaScript programs may generate unexpected results if a programmer accidentally uses an assignment operator (=), instead of a comparison operator (==) in an if statement. When using x = 10 inside an if condition, JavaScript assigns the value 10 to x and returns true because 10 is a truthy value. Similarly, x = 0 returns false because 0 is falsy.
π Definition β Assignment Operator: The = operator assigns a value to a variable, while == compares values.
π Formula: if (x = 10) β This assigns 10 to x and evaluates as true, instead of comparing x to 10
π Example:
var x = 0;
if (x = 10) // Returns true because 10 is truthy, x becomes 10
if (x = 0) // Returns false because 0 is falsy, x becomes 0
Expecting Loose Comparison
In regular comparison using ==, data type does not matter. In strict comparison using ===, data type does matter. This is a common source of bugs when developers expect type coercion to work in specific ways.
π Definition β Loose vs Strict Comparison: == compares values after type conversion; === compares both value and type without conversion π Example:
var x = 10;
var y = "10";
if (x == y) // Returns true (loose comparison)
if (x === y) // Returns false (strict comparison - different types)
Switch Statement
It is a common mistake to forget that switch statements use strict comparison. If the case value type doesn't match the variable type, the case won't execute.
π Example:
var x = 10;
switch(x) {
case 10: alert("Hello"); // Works - matches type and value
}
switch(x) {
case "10": alert("Hello"); // Won't work - string vs number
}
Confusing Addition & Concatenation
Addition is about adding numbers. Concatenation is about adding strings. In JavaScript both operations use the same + operator. When one operand is a string, JavaScript converts the other operand to a string and concatenates.
π Example:
var x = 10, y = 5;
var z = x + y; // z = 15 (numeric addition)
var x = 10, y = "5";
var z = x + y; // z = "105" (string concatenation)
Misunderstanding Floats
All numbers in JavaScript are stored as 64-bits Floating point numbers (Floats). All programming languages have difficulties with precise floating point values.
π Example:
var x = 0.1, y = 0.2;
var z = x + y; // z will not be exactly 0.3
if (z == 0.3) // This if test will fail
var z = (x * 10 + y * 10) / 10; // Solution: multiply and divide to get 0.3
π‘ Why this matters: Floating point precision issues cause calculation errors in financial and scientific applications if not handled properly.
Breaking a JavaScript String
JavaScript allows breaking a statement into two lines, but breaking a statement in the middle of a string will not work. You must use a backslash if you must break a string.
π Example:
var x = "Hello \
World!"; // Valid - backslash allows string continuation
// var x = "Hello // Invalid - string broken mid-value
// World!";
Misplacing Semicolon
Because of a misplaced semicolon, a code block will execute regardless of the value of x.
π Example:
if (x == 19); // Semicolon ends the if statement here
{ // This block always executes
// code block
}
Breaking a Return Statement
It is a default JavaScript behavior to automatically close a statement at the end of a line. If you break a return statement onto a new line, the function will return undefined.
π Example:
function myFunction(a) {
var power = 10;
return // JavaScript adds semicolon here automatically
a * power; // This line is never reached
// Function returns undefined
}
Accessing Arrays with Named Indexes
JavaScript does not support arrays with named indexes. Arrays use numbered indexes, while objects use named indexes. Using named indexes on an array will redefine the array to a standard object.
π Example:
var person = [];
person[0] = "John"; // Correct - numbered index
person["firstName"] = "John"; // Incorrect - converts array to object
var x = person.length; // Returns 0 for object
Ending an Array or Object Definition with a Comma
Trailing commas in array or object definitions can cause JSON and JavaScript engines to fail or behave unexpectedly.
π Incorrect:
points = [40, 100, 1, 5, 25, 10,]; // Trailing comma
person = {firstName:"John", lastName:"Doe", age:46,} // Trailing comma
π Correct:
points = [40, 100, 1, 5, 25, 10];
person = {firstName:"John", lastName:"Doe", age:46}
Undefined is Not Null
With JavaScript, null is for objects, undefined is for variables, properties, and methods. To be null, an object must be defined. You must test typeof() before checking if an object exists.
π Definition β Null vs Undefined: null is an intentional absence of object value; undefined means a variable has been declared but not assigned a value
π Example:
// Incorrect - throws error if myObj is undefined
if (myObj !== null && typeof myObj !== "undefined")
// Correct - test typeof first
if (typeof myObj !== "undefined" && myObj !== null)
Expecting Block Level Scope
JavaScript does not create a new scope for each code block. Variables declared with var inside code blocks (like if statements or loops) are accessible outside those blocks. Block-level scoping with let and const was introduced in ES6.
β Key Takeaways
Always use strict comparison (===) instead of loose comparison (==) to avoid unexpected type coercion, and never use assignment operators (=) in conditional statements. Remember that JavaScript uses strict comparison in switch statements and has automatic semicolon insertion that can break return statements. Arrays must use numbered indexes only, and objects use named indexes. Floating point arithmetic requires special handling through multiplication and division. Always test typeof() before checking if an object exists, and never end array or object definitions with trailing commas in JSON-compatible code.
π§ Quick Revision Questions
- What is the difference between loose comparison (==) and strict comparison (===) in JavaScript?
- Why does
var z = 0.1 + 0.2not equal exactly 0.3, and how can this be fixed? - What happens when you use named indexes on an array instead of numbered indexes?
- Why does breaking a return statement onto a new line cause the function to return undefined?
- What is the correct order for checking if an object exists: should you check for null or typeof() first?
π Lecture 88 β JavaScript Global Functions and Properties
π Overview: This lecture introduces several global JavaScript properties and functions that are available across all built-in JavaScript objects. It explains the meaning and usage of properties like
Infinity,NaN, andundefined, and theeval()function, while also providing a caution about the deprecatedconstkeyword.
ποΈ Topics Covered
The lecture begins by warning against using the const keyword as it is not a standard part of older JavaScript versions (ES3 or ES5). It then defines the global properties Infinity, NaN, and undefined, followed by the eval() function with examples of how it evaluates expressions and executes statements. The lecture concludes by advising against the use of eval() unless absolutely necessary.
π Lecture Summary
Const is an extension to JavaScript. It is supported by the JavaScript engine used in Firefox and Chrome. But it is a part of the JavaScript standards ES3 or ES5. Do not use it.
const is an extension to JavaScript but is not part of the ECMAScript 3 (ES3) or ES5 standards. While supported in Firefox and Chrome, using it is not recommended because it may not be supported in all environments.
88- JavaScript Global Functions and Properties
The JavaScript global properties and functions can be used with all the built-in JavaScript objects. They are accessible from anywhere in your code without needing to reference a specific object.
π Definition β Infinity: A numeric value that represents positive or negative infinity. It is displayed when a number exceeds the upper or lower limit of the floating point numbers. π Definition β NaN: The "Not-a-Number" value property. It indicates that a value is not a legal number. π Definition β undefined: Indicates that a variable has not been assigned a value.
π Definition β eval(): A global function that evaluates a string and executes it as if it were script code. If the argument is an expression, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements.
π Example: The eval() function can evaluate simple mathematical expressions or operations involving variables.
var x = 10;
var y = 20;
var a = eval("x * y"); // 200
var b = eval("2 + 2"); // 4
var c = eval("x + 17"); // 27
π Example: You can execute any JavaScript statement using eval().
π‘ Why this matters: eval() can execute arbitrary code, which is a major security risk. It is not recommended to use it unless you have no other choice.
β Key Takeaways
The lecture emphasizes that const is not part of the ES3 or ES5 standards and should be avoided for compatibility. It introduces the global properties Infinity, NaN, and undefined for handling numeric limits, illegal numbers, and unassigned variables. The eval() function is explained as a powerful but dangerous tool for executing string-based code. The primary takeaway is to understand these built-in features while being mindful of browser compatibility and security implications.
π§ Quick Revision Questions
- Why is it recommended to avoid using the
constkeyword in JavaScript according to this lecture? - What does the global
NaNproperty represent, and when would it occur? - What is the primary purpose of the
eval()function? - Give an example of how the
Infinityproperty might be triggered in a JavaScript program. - What is the value of a variable that has been declared but has not been assigned a value?