Client-Side JavaScript:
Server-Side JavaScript:
JavaScript | Java |
---|---|
Object-oriented. No distinction between types of objects. Inheritance is through the prototype mechanism, and properties and methods can be added to any object dynamically. | Class-based. Objects are divided into classes and instances with all inheritance through the class hierarchy. Classes and instances cannot have properties or methods added dynamically. |
Variable data types are not declared (dynamic typing, loosely typed). | Variable data types must be declared (static typing, strongly typed). |
Cannot automatically write to hard disk. | Can automatically write to hard disk. |
Recent versions of Firefox, Chrome, Microsoft Edge, and Safari all support the features discussed in this guide.
Statements:
;
)Semicolon Usage:
Best Practice:
Source Text:
Whitespace:
// a one line comment
/* this is a longer,
* multi-line comment
*/
Comment Behavior:
Hashbang Comments:
#!/usr/bin/env node
(for specifying a JS engine)// Bindings
var mainAxis = "row";
let i = 10;
const dot = ".";
var
: Declares a variable (function/global scope)let
: Declares a block-scoped variableconst
: Declares a block-scoped, read-only constantlet mood = "light";
console.log(mood);
mood = "dark";
console.log(mood);
Can be any word, digits, $ and _
but the name must not start with a digit
{}
(for let
and const
)if (Math.random() > 0.5) {
const y = 5;
}
console.log(y); // ReferenceError: y is not defined
var
declarations are hoistedlet
and const
declarations are not hoisted to the top of their blocklet
or const
cannot be accessed before declarationconsole.log(x); // undefined
var x = 3;
function test() {
console.log(y); // undefined
var y = "local value";
}
Global Object:
window
window.variable
or globalThis.variable
to access globalsCross-window Access:
parent.variableName
const PI = 3.14;
const MY_OBJECT = { key: "value" };
MY_OBJECT.key = "otherValue"; // Allowed
const MY_ARRAY = ["HTML", "CSS"];
MY_ARRAY.push("JAVASCRIPT");
console.log(MY_ARRAY); // ['HTML', 'CSS', 'JAVASCRIPT'];
The collection of bindings and their values that exist at a given time is called the environment.
var nombre = prompt("Ingrese su Nombre");
var mensaje = `Hola ${nombre}, que hermoso eres`;
console.log(mensaje);
alert(mensaje);
Seven data types that are primitives:
and
fixed with 64 bits
// All the following values are Numbers
10
-10
10.2
-10.2
console.log(typeof 10);
// 10 x 10 ^ 2
10e2;
// -10 x 10 ^ 3
-10e3;
// Operators
10 + 11;
10 - 11;
10 * 20;
13 / 40;
40 % 2;
Arithmetic Operators: These are used to perform basic mathematical operations.
// Hierarchy of operators
3 + 5 / 2(3 + 5) / 2;
Operator Hierarchy (Order of Operations): JavaScript follows the standard mathematical order of operations, also known as "PEMDAS" (Parentheses, Exponents, Multiplication and Division, Addition and Subtraction). Operations within parentheses are executed first, followed by division, and then addition.
// Infinity AND -Infinity
1 / 0; -1 / 0;
// NaN
0 / 0;
Infinity and -Infinity: In JavaScript, dividing a number by zero results in Infinity
or -Infinity
, depending on the sign of the number.
NaN (Not-a-Number): This special value represents an undefined or unrepresentable value, particularly in arithmetic operations where the result is not a real number, such as dividing zero by zero.
16 bits per string element
// String Values
'I am a String'
"I am a String"
'Scape character \' '
"Scape character \" "
' Multiline
line 2 '
// Template String
`half of 100 is ${100 / 2}` // half of 100 is 50
// String Values
"a" + "b";
"a".length;
"abcdefg"[0];
"abcdefg"[3];
"a,b,c,d".split(",");
" ok ".trim(); // "OK"
// Boolean Values
true
false
5 > 2
5 >= 2
3 < 4
4 <= 4
5 != 5
5 == 5
"5" == 5
5 === 5
"5" !== 5
// Boolean Values
true
false
null || 2
null && 2
true || false
true && false
!true
!false
NaN == NaN // → false
console.log(null || "user")
// → user
console.log("Agnes" || "user")
// → Agnes
let answer = 42;
// No error, type is dynamically changed
answer = "Thanks for all the fish!";
+
operator can lead to type conversion when used with strings and numbers.+
.x = "The answer is " + 42; // Result: "The answer is 42"
y = 42 + " is the answer"; // Result: "42 is the answer"
z = "37" + 7; // Result: "377"
+
do not convert numbers to strings."37" - 7; // Result: 30
"37" * 7; // Result: 259
+
): Converts a string directly to a number.parseInt("101", 2); // Result: 5 (binary to decimal conversion)
"1.1" + "1.1"; // Result: "1.11.1" (string concatenation)
(+"1.1") + (+"1.1"); // Result: 2.2 (number addition)
[]
.const coffees = ["French Roast", "Colombian", "Kona"];
function createArray() {
const array = ["Item1", "Item2"];
// New array created on each function call
}
Extra Commas in Array Literals
const fish = ["Lion", , "Angel"];
// Result: [ 'Lion', <1 empty item>, 'Angel' ]
const myList = ["home", , "school"];
// Length: 3, myList[1] is empty
const myList2 = [, "home", , "school"];
// Length: 4, myList[0] and myList[2] are missing
const myList3 = ["home", , "school", ,];
// Length: 4, myList[1] and myList[3] are missing
Trailing Commas: Help keep git diffs clean by adding one line for new elements.
const myList = [
"home",
"school",
+ "hospital",
];
// Expressions
10 + 5 <= 10 + 6
let x = 10,
y = "a";
console.log( y === b || x >= 10 );
Which is the result?
{
statement1;
statement2;
// …
statementN;
}
The most basic statement is a block statement, which is used to group statements. The block is delimited by a pair of curly braces
// IF
if (2 >= 3) {
console.log(0);
} else {
console.log(1);
}
if (2 >= 3) {
console.log(0);
} else if( 4 < 2) {
console.log(1);
} else {
console.log(2);
}
switch (prompt("What is the weather like?")) {
case "rainy":
console.log("Remember to bring an umbrella.");
break;
case "sunny":
console.log("Dress lightly.");
case "cloudy":
console.log("Go outside.");
break;
default:
console.log("Unknown weather type!");
break;
}
// Loop While
let a = 10;
while (a >= 0) {
console.log(a);
a--;
}
// Loop Do While
do {
console.log(a);
a++
} while(a <= 10);
for(let i = 0 ; i <= 10 ; i++) {
console.log(i);
}
// The are other syntax, see the next slides
The following values evaluate to false (also known as Falsy values):
undefined
null
0
NaN
the empty string ("")
throw
StatementPurpose: To throw an exception with a specified value.
throw expression;
throw "Error2"; // String type
throw 42; // Number type
throw true; // Boolean type
throw {
toString() {
return "I'm an object!";
},
};
try...catch
StatementPurpose: To catch and handle exceptions.
try {
// Statements to try
} catch (exception) {
// Statements to handle the exception
}
function getMonthName(mo) {
mo--; // Adjust month number for array index
const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
if (months[mo]) {
return months[mo];
} else {
throw new Error("InvalidMonthNo");
}
}
try {
monthName = getMonthName(myMonth);
} catch (e) {
monthName = "unknown";
logMyErrors(e); // Handle the error
}
finally
BlockPurpose: To execute statements after try and catch blocks, regardless of whether an exception was thrown
openMyFile();
try {
writeMyFile(theData);
} catch (e) {
handleError(e);
} finally {
closeMyFile(); // Always executed
}
try...catch
Statementstry
blocks must have a finally
block if they don't have their own catch
block.try...catch
statement's catch
block handles exceptions if no inner catch
block is present.name
: General class of the error (e.g., DOMException
).message
: Detailed error message.function doSomethingErrorProne() {
if (ourCodeMakesAMistake()) {
throw new Error("The message");
} else {
doSomethingToGetAJavaScriptError();
}
}
try {
doSomethingErrorProne();
} catch (e) {
console.error(e.name); // 'Error'
console.error(e.message); // 'The message'
}
Function Declarations: Consist of:
function
keywordParameters: Passed by value. Changes to objects or arrays inside the function affect the original object or array.
function square(number) {
return number * number;
}
Arguments are optional if you pass too many, the extra ones are ignored. If you pass too few, the missing parameters get assigned the value undefined.
function minus(a, b) {
if (b === undefined) return -a;
else return a - b;
}
console.log(minus(10));
console.log(minus(10, 5));
function power(base, exponent = 2) {
let result = 1;
for (let count = 0; count < exponent; count++) {
result *= base;
}
return result;
}
Objects: Changes to object properties are visible outside the function.
function myFunc(theObject) {
theObject.make = "Toyota";
}
const mycar = {
make: "Honda",
model: "Accord",
year: 1998,
};
console.log(mycar.make); // "Honda"
myFunc(mycar);
console.log(mycar.make); // "Toyota"
Arrays: Changes to array elements are visible outside the function.
function myFunc(theArr) {
theArr[0] = 30;
}
const arr = [45];
console.log(arr[0]); // 45
myFunc(arr);
console.log(arr[0]); // 30
const square = function (number) {
return number * number;
};
console.log(square(4)); // 16
const factorial = function fac(n) {
return n < 2 ? 1 : n * fac(n - 1);
};
console.log(factorial(3)); // 6
function map(f, a) {
const result = new Array(a.length);
for (let i = 0; i < a.length; i++) {
result[i] = f(a[i]);
}
return result;
}
const cube = function (x) {
return x * x * x;
};
const numbers = [0, 1, 2, 5, 10];
console.log(map(cube, numbers)); // [0, 1, 8, 125, 1000]
Functions can be defined conditionally.
let myFunc;
if (num === 0) {
myFunc = function (theObject) {
theObject.make = "Toyota";
};
}
const num1 = 20;
const num2 = 3;
const name = "Chamakh";
function multiply() {
return num1 * num2;
}
console.log(multiply()); // 60
function getScore() {
const num1 = 2;
const num2 = 3;
function add() {
return `${name} scored ${num1 + num2}`;
}
return add();
}
console.log(getScore()); // "Chamakh scored 5"
is the combination of a function and the lexical environment within which that function was declared.
A closure is a function that remembers its lexical scope even when it's executed outside of that scope. In simpler terms, it's a function that "remembers" the variables and the environment in which it was created.
function multiplier(factor) {
return number => number * factor;
}
let twice = multiplier(2);
console.log(twice(5));
function A(x) {
function B(y) {
function C(z) {
console.log(x + y + z);
}
C(3);
}
B(2);
}
A(1); // Logs 6
When variables or parameters with the same name exist in different scopes, the innermost scope takes precedence.
function outside() {
const x = 5;
function inside(x) {
return x * 2;
}
return inside;
}
console.log(outside()(10)); // 20
Private variables: Closures allow you to create variables that are only accessible from within the inner function, simulating the behavior of private variables in object-oriented languages.
Callbacks and events: They are essential for handling callbacks and events in JavaScript, allowing a function to access variables from an outer scope.
Modules: Closures are used to create modules, encapsulating related code and data.
Currying: Currying, a technique for transforming functions with multiple arguments into a sequence of functions with a single argument, relies on closures
function min(...numbers) {
let result = Infinity;
for (let number of numbers) {
if (number < result) result = number;
}
return result;
}
let words = ["never", "fully"];
console.log(["will", ...words, "understand"]);
this
, arguments
, super
, or new.target
.Will work more in the next slides
// binding function
function play() {
console.log("Ta Ta Taaaaaaaaaaaaa");
}
var scream = function () {
console.log("Aaaaahhhh!!")
};
var motivate = () => {
console.log("Just do it!")
}
Arrays are a fundamental data structure in JavaScript. They allow you to store multiple items under a single variable name. This makes it easier to manage and work with collections of data.
[]
).Array()
constructor can also be used to create arrays. However, it is generally less common than the array literal syntax. const fruits = ['apple', 'banana', 'orange'];
const numbers = new Array(1, 2, 3, 4, 5);
You can access individual elements of an array using their index. The index starts from 0, so the first element has an index of 0, the second element has an index of 1, and so on.
const firstFruit = fruits[0];
Arrays have a number of built-in properties and methods that allow you to perform various operations on them. Here are some commonly used ones:
let list = [2, 3, 5, 7, 11];
list.push(12); // Add an element in the end of array
console.log(list);
console.log(list.pop()); // Extract a last element of array
console.log(list);
list.unshift(1); // Add an element beginning of the array
list.shift(1); // Extract an element beginning of the array
console.log(list.indexOf(2))
console.log(list.slice(2,5));
console.log(list.slice(5));
console.log(list.concat([1,3,4,5]));
const array1 = ['a', 'b', 'c'];
for (const element of array1) {
console.log(element);
}
Date
object provides methods to work with dates and times.const now = new Date();
console.log(now); // Outputs the current date and time
const specificDate = new Date('2024-09-01T10:00:00');
console.log(specificDate); // Outputs: Sat Sep 01 2024 10:00:00 GMT...
const dateFromComponents = new Date(2024, 8, 1, 10, 0, 0); // Note: Month is zero-indexed
console.log(dateFromComponents); // Outputs: Sun Sep 01 2024 10:00:00 GMT...
const date = new Date();
console.log(date.getFullYear()); // Outputs the current year
console.log(date.getMonth()); // Outputs the current month (0-11)
console.log(date.getDate()); // Outputs the current day of the month
console.log(date.getHours()); // Outputs the current hour
console.log(date.getMinutes()); // Outputs the current minute
console.log(date.getSeconds()); // Outputs the current second
const date = new Date();
date.setFullYear(2025);
date.setMonth(11); // December
date.setDate(25);
console.log(date); // Outputs: Thu Dec 25 2025 ...
date.setHours(15);
date.setMinutes(30);
date.setSeconds(45);
console.log(date); // Outputs: Thu Dec 25 2025 15:30:45 GMT...
const date = new Date();
console.log(date.toDateString()); // Outputs: Fri Sep 01 2024
console.log(date.toTimeString()); // Outputs: 10:00:00 GMT+0000 (Coordinated Universal Time)
console.log(date.toLocaleDateString()); // Outputs: 9/1/2024 (depends on locale)
console.log(date.toLocaleTimeString()); // Outputs: 10:00:00 AM (depends on locale)
const date = new Date();
const futureDate = new Date(date);
futureDate.setDate(date.getDate() + 10); // Add 10 days
console.log(futureDate); // Outputs: (Date 10 days from now)
const date1 = new Date();
const date2 = new Date('2024-09-01');
const diffInMilliseconds = date2 - date1;
const diffInDays = diffInMilliseconds / (1000 * 60 * 60 * 24);
console.log(diffInDays); // Outputs the difference in days
const date = new Date();
console.log(date.toUTCString()); // Outputs date in UTC timezone
console.log(date.toLocaleString()); // Outputs date and time in local timezone
What are Regular Expressions?
Literal Characters:
const regex = /hello/;
console.log(regex.test("hello world")); // true
Metacharacters:
.
, *
, +
, ?
, ^
, $
, etc.Dot (.
):
const regex = /h.llo/;
console.log(regex.test("hello")); // true
console.log(regex.test("hallo")); // true
Asterisk (*
):
const regex = /ho*/;
console.log(regex.test("hoop")); // true
console.log(regex.test("h")); // true
Character Classes:
\d
matches any digit (0-9).\w
matches any word character (alphanumeric plus underscore).\s
matches any whitespace character.const regex = /\d/;
console.log(regex.test("There are 3 apples")); // true
Character Sets:
[]
.[a-z]
matches any lowercase letter.[A-Z]
matches any uppercase letter.const regex = /[a-z]/;
console.log(regex.test("Hello")); // true
*
- Matches 0 or more times.+
- Matches 1 or more times.?
- Matches 0 or 1 time.{n}
- Matches exactly n times.{n,}
- Matches at least n times.{n,m}
- Matches between n and m times.const regex = /\d{2,4}/;
console.log(regex.test("123")); // true
console.log(regex.test("1")); // false
^
):
$
):
const regex = /^hello/;
console.log(regex.test("hello world")); // true
console.log(regex.test("world hello")); // false
const regex = /\bworld\b/;
console.log(regex.test("hello world!")); // true
console.log(regex.test("helloworld")); // false
Grouping:
()
are used to group expressions.const regex = /(abc)+/;
console.log(regex.test("abcabc")); // true
Flags modify the behavior of a regex search:
i
: Case-insensitive search.g
: Global search.m
: Multi-line search.const regex = /hello/i;
console.log(regex.test("Hello")); // true
test()
:
true
or false
.const regex = /\d+/;
console.log(regex.test("123")); // true
match()
:
null
.const regex = /\d+/g;
console.log("There are 123 and 456".match(regex)); // ["123", "456"]
replace()
:
const regex = /apples/g;
console.log("I like apples".replace(regex, "oranges")); // "I like oranges"
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(regex.test("example@example.com")); // true
const regex = /^\d{4}-\d{4}$/; // salvadoren format
console.log(regex.test("123-456-7890")); // true
An object is a collection of properties, each with a name (or key) and a value
Object Literals:
{ key1: value1, key2: value2, ... }
const car = {
make: "Ford",
model: "Mustang",
year: 1969
};
Constructor Functions:
new
keyword.function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
const myCar = new Car("Ford", "Mustang", 1969);
{ property1: value1, property2: value2, ... }
const person = {
name: "John",
age: 30,
job: "Engineer"
};
this
keyword to define properties.function Person(name, age) {
this.name = name;
this.age = age;
}
const person1 = new Person("Alice", 25);
Object.create(proto,[propertiesObject])
const animal = {
type: "Invertebrates",
displayType() {
console.log(this.type);
}
};
const fish = Object.create(animal);
fish.type = "Fishes";
fish.displayType(); // Logs: "Fishes"
objectName.propertyName
objectName["propertyName"]
let person = {
name: "Néstor",
lastname: "Aldana",
};
console.log(person.name);
console.log(person.age); // Undefined
person.age = 23; // defined later
person.name = "Nexxtor" // Change value
console.log(person.age);
delete person.age; // Delete a property
console.log(person.age);
console.log("age" in person); // Age exists in person?
console.log("name" in person); // Name exists in person?
for...in
loop for enumerable properties.Object.keys()
returns an array of property names.Object.getOwnPropertyNames()
returns all property names, enumerable or not.const obj = { a: 1, b: 2 };
for (const key in obj) {
console.log(key, obj[key]);
}
objectName.newProperty = value;
objectName["newProperty"] = value;
delete objectName.propertyName;
const myObj = { name: "Alice" };
myObj.age = 25; // Add a property
delete myObj.name; // Delete a property
function Animal(type) {
this.type = type;
}
Animal.prototype.speak = function() {
console.log(`The ${this.type} speaks.`);
};
const cat = new Animal("cat");
cat.speak(); // Outputs: "The cat speaks."
Functions that are properties of objects.
Prototype Methods:
const car = {
make: "Toyota",
drive() {
console.log("Driving...");
}
};
Car.prototype.start = function() {
console.log("Car started");
};
this
in Objectsthis
Keyword:
const person = {
name: "Bob",
greet() {
console.log(`Hello, my name is ${this.name}`);
}
};
person.greet(); // Outputs: "Hello, my name is Bob"
function normalize() {
console.log(this.coords.map(n => n / this.length));
}
normalize.call({coords: [0, 2, 3], length: 5});
Arrow functions and this
let empty = {};
console.log(empty.toString);
console.log(empty.toString());
console.log(Object.getPrototypeOf({}) == Object.prototype);
console.log(Object.getPrototypeOf(Object.prototype));
let object1 = {value: 10};
let object2 = object1;
let object3 = {value: 10};
console.log(object1 == object2); // true
console.log(object1 == object3); // false
object1.value = 15;
console.log(object2.value); // 15
console.log(object3.value); // 10
JavaScript’s == operator, it compares objects by identity
const [a, b] = array;
const [a, , b] = array;
const [a = aDefault, b] = array;
const [a, b, ...rest] = array;
const [a, , b, ...rest] = array;
const [a, b, ...{ pop, push }] = array;
const [a, b, ...[c, d]] = array;
const { a, b } = obj;
const { a: a1, b: b1 } = obj;
const { a: a1 = aDefault, b = bDefault } = obj;
const { a, b, ...rest } = obj;
const { a: a1, b: b1, ...rest } = obj;
const { [key]: a } = obj;
let a, b, a1, b1, c, d, rest, pop, push;
[a, b] = array;
[a, , b] = array;
[a = aDefault, b] = array;
[a, b, ...rest] = array;
[a, , b, ...rest] = array;
[a, b, ...{ pop, push }] = array;
[a, b, ...[c, d]] = array;
({ a, b } = obj); // parentheses are required
({ a: a1, b: b1 } = obj);
({ a: a1 = aDefault, b = bDefault } = obj);
({ a, b, ...rest } = obj);
({ a: a1, b: b1, ...rest } = obj);
function phi([n00, n01, n10, n11]) {
return (n11 * n00 - n10 * n01) /
Math.sqrt((n10 + n11) * (n00 + n01) *
(n01 + n11) * (n00 + n10));
}
let {name} = {name: "Faraji", age: 23};
console.log(name);
class MyClass {
constructor(prop1, prop2) {
this.prop1 = prop1;
this.prop2 = prop2;
}
method1() {
console.log('This is method 1');
}
method2() {
console.log('This is method 2');
}
}
const instance = new MyClass('value1', 'value2');
console.log(instance.prop1); // Output: value1
instance.method1(); // Output: This is method 1
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Rex');
dog.speak(); // Output: Rex barks.
class MathUtility {
static add(a, b) {
return a + b;
}
}
console.log(MathUtility.add(5, 10)); // Output: 15
class Rectangle {
#height = 0;
#width = 0;
constructor(height, width) {
this.#height = height;
this.#width = width;
}
#calculateArea() {
return this.#height * this.#width;
}
getArea() {
return this.#calculateArea();
}
}
const rect = new Rectangle(10, 5);
console.log(rect.getArea()); // Output: 50
// console.log(rect.#height); // Error: Private field '#height' must be declared in an enclosing class
class Person {
constructor(name) {
this._name = name;
}
get name() {
return this._name;
}
set name(newName) {
this._name = newName;
}
}
const person = new Person('Alice');
console.log(person.name); // Output: Alice
person.name = 'Bob';
console.log(person.name); // Output: Bob
Notes: JSON is language-independent but uses conventions familiar to programmers of the C family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others.
Notes: JSON syntax is derived from JavaScript object notation syntax but is text-only, making it language-independent and ideal for data exchange.
{
"key": "value"
}
["red", "green", "blue"]
{
"firstName": "John",
"lastName": "Doe"
}
{
"name": "Jane Doe",
"age": 30,
"isStudent": false,
"courses": ["Mathematics", "Computer Science"],
"address": {
"street": "123 Main St",
"city": "Anytown",
"zip": "12345"
}
}
JSON is typically preferred over XML for data interchange due to its simplicity and ease of use with JavaScript, but XML remains in use for complex documents and when strict validation is needed.
const jsonString = '{"name": "John", "age": 25}';
const jsonObject = JSON.parse(jsonString);
console.log(jsonObject.name); // Output: John
const jsObject = { name: "Jane", age: 30 };
const jsonStr = JSON.stringify(jsObject);
console.log(jsonStr); // Output: {"name":"Jane","age":30}
Web APIs: Used to exchange data between client and server.
Configuration Files: Storing settings and configurations.
Data Storage: Storing data in NoSQL databases like MongoDB.
Data Interchange: Sharing data between different systems or applications.
What are Symbols in JavaScript?
Notes: Unlike other primitive data types, each symbol is unique, even if two symbols have the same description.
Symbols are created using the Symbol() function.
The description is optional and used for debugging purposes; it does not affect the symbol's uniqueness.
let mySymbol = Symbol();
let anotherSymbol = Symbol('description');
Symbols provide a way to add unique property keys to objects without risking property name collisions.
Symbols can be used as unique keys in objects.
Using symbols as object keys helps prevent accidental property overwrites or conflicts with other keys.
const sym1 = Symbol('key1');
const obj = {};
obj[sym1] = 'value1';
console.log(obj[sym1]); // Output: 'value1'
const globalSym = Symbol.for('globalKey');
console.log(Symbol.keyFor(globalSym)); // Output: 'globalKey'
Symbols offer a way to define unique keys and behaviors that help avoid naming collisions and enable advanced programming patterns.
These limitations are by design, enhancing security and ensuring that symbols provide unique, non-colliding property keys.
Create an object that registers a list (Array) of a person's life events in a single day, and a boolean property to check if that person has had an accident during that day
let day = {
events : ["cook", "sleep", "running"],
accident: false
};
let journal = [
{
events: ["work", "touched tree", "pizza",
"running", "television"],
accident: false
},
{
events: ["work", "ice cream", "cauliflower",
"lasagna", "touched tree", "brushed teeth"],
accident: false
},
{
events: ["weekend", "cycling", "break",
"peanuts","beer"],
accident: true
}
]
let journal = [];
function addEntry(events, accident) {
journal.push({events, accident});
/******************************************
* Is {events, accident} shorthand to *
* {events: events, accident: accident} *
*****************************************/
}
addEntry(["weekend", "cycling", "break", "peanuts", "beer"]
, true);
addEntry(["weekend", "cycling", "break"], false);
Functions that operate on other functions
function repeat(n, action) {
for (let i = 0; i < n; i++) {
action(i);
}
}
let departments = [];
repeat(5, i => departments.push(`Department ${i}`));
console.log({departments}); // Only for get a name of the var
function lessThan(n) {
return m => m < n;
}
let lessThan10 = lessThan(10);
console.log(lessThan10(4));
function unless(test, then) {
if (!test) then();
}
unless( 2 > 3, n => console.log("ok"))
["A", "B"].forEach(i => console.log(i));
function filter(array, test) {
let passed = [];
for (let element of array) {
if (test(element)) {
passed.push(element);
}
}
return passed;
}
filter([1,3,5,6,7,10], e => e % 2 == 0);
console.log([1,3,5,6,7,10].filter(e => e % 2 == 0));
function map(array, transform) {
let mapped = [];
for (let element of array) {
mapped.push(transform(element));
}
return mapped;
}
let cars = [{ brand: "Toyota", year: "1990"},
{ brand: "Dogge", year: "2020"},
{ brand: "Pollito", year: "2018"},];
map(cars, e=> e.brand);
let cars = [{ brand: "Toyota", year: "1990"},
{ brand: "Dogge", year: "2020"},
{ brand: "Pollito", year: "2018"},];
cars.map(e => e.brand);
function reduce(array, combine, start) {
let current = start;
for (let element of array) {
current = combine(current, element);
}
return current;
}
console.log(reduce([1, 2, 3, 4], (a, b) => a + b, 0));