JavaScript Fundamentals: Console, Variables, Data Types, and Objects

The provided text is a guide to understanding JavaScript programming concepts. It covers a range of topics, beginning with how to use the console for debugging. The text then explores fundamental concepts such as variables, data types (primitive and reference), type coercion, and operators. It discusses strings, numbers, arrays, and objects, including methods to manipulate them. Finally, it introduces functions, scope, DOM manipulation, and event handling, along with keyboard events.

JavaScript Fundamentals Study Guide

Quiz

  1. What are the three core technologies of the web?
  2. Explain the difference between interpreted and compiled code.
  3. Briefly describe the Document Object Model (DOM).
  4. What is an asynchronous request, and why is it useful in web development?
  5. What is the purpose of the parseFloat() function? How does it differ from parseInt()?
  6. Explain the concept of “truthy” and “falsy” values in JavaScript, and give one example of each.
  7. What does NaN represent in JavaScript, and list two operations that result in NaN.
  8. Describe what the modulus operator (%) does.
  9. Explain the difference between == and === comparison operators in JavaScript.
  10. What is type coercion in JavaScript, and how does it differ from type conversion?

Quiz Answer Key

  1. HTML, CSS, and JavaScript. HTML structures web content, CSS styles the content, and JavaScript brings interactivity to the front-end.
  2. Interpreted code is executed line by line, while compiled code is first translated into machine code before execution. JavaScript is an interpreted language, making it a scripting language.
  3. The DOM is a tree-like structure of nodes representing everything on a web page, including HTML tags, attributes, and text. JavaScript can manipulate the DOM to dynamically change the content and styles of elements.
  4. An asynchronous request allows a web page to interact with a back-end server without requiring a page refresh. This is useful for dynamically loading and updating content, particularly in single-page applications.
  5. The parseFloat() function converts a string to a floating-point number. parseInt() converts a string to an integer, discarding any decimal portion.
  6. Truthy values are values that evaluate to true in a Boolean context (e.g., 1, “hello”), while falsy values evaluate to false (e.g., 0, null, undefined, “”).
  7. NaN stands for “Not a Number,” representing a value that is not a valid number. Operations such as parsing a non-numeric string with parseInt() or parseFloat(), or square root of a negative number result in NaN.
  8. The modulus operator (%) returns the remainder of a division operation. For example, 7 % 5 equals 2.
  9. The == operator compares two values for equality after type coercion, meaning JavaScript might try to convert the values to a common type before comparing them. The === operator compares two values for equality without type coercion, meaning the values must be of the same type to be considered equal.
  10. Type coercion is the implicit conversion of one data type to another by JavaScript, often when applying operators to values of different types. Type conversion is the explicit conversion of one data type to another by the developer, using functions like String(), Number(), and Boolean().

Essay Questions

  1. Discuss the versatility of JavaScript and the reasons for its popularity in modern web development.
  2. Explain the differences between client-side and server-side JavaScript. Give examples of frameworks or environments associated with each.
  3. Describe the concept of scope in JavaScript, differentiating between global, function, and block scope. Use examples to illustrate how variable access changes in different scopes.
  4. Explain the execution context in JavaScript, including the memory creation phase and execution phase. How does the execution context differ when invoking a function?
  5. Describe the different types of keyboard events in JavaScript and how they are used. Include details about properties like key, keyCode and code and how to use modifier properties such as shiftKey, ctrlKey and altKey.

Glossary of Key Terms

  • API (Application Programming Interface): A set of rules and specifications that software programs can follow to communicate with each other.
  • Asynchronous Request: A request that doesn’t block the execution of other code while waiting for a response.
  • Boolean: A data type with two possible values: true or false.
  • Client-Side JavaScript: JavaScript code that runs in the user’s web browser.
  • Compiled Code: Code that has been translated into machine code by a compiler before execution.
  • CSS (Cascading Style Sheets): A style sheet language used for describing the presentation of a document written in a markup language like HTML.
  • DOM (Document Object Model): A programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content.
  • Event: An action or occurrence recognized by a software system, often originating asynchronously from the external environment, such as a mouse click or key press.
  • Expression: A combination of values, variables, operators, and function calls that evaluates to a single value.
  • Falsy Value: A value that evaluates to false in a Boolean context (e.g., 0, “”, null, undefined, NaN).
  • Function: A block of organized, reusable code that performs a specific task.
  • Global Scope: The scope that contains variables that are declared outside of any function or block.
  • Hoisting: The JavaScript mechanism where declarations of variables and functions are moved to the top of their scope before code execution.
  • HTML (HyperText Markup Language): The standard markup language for creating web pages.
  • HTTP Request: A request made by a client to a server to access resources or perform actions.
  • IIFE (Immediately Invoked Function Expression): A JavaScript function that runs as soon as it is defined.
  • Interpreted Code: Code that is executed line by line by an interpreter.
  • JavaScript: A high-level, interpreted programming language primarily used for creating interactive web pages.
  • Local Storage: A web storage API that allows web applications to store data locally within the user’s browser.
  • NaN (Not a Number): A value representing an undefined or unrepresentable value, typically resulting from invalid mathematical operations.
  • Node.js: A JavaScript runtime environment that allows JavaScript to be used on the server side.
  • Operator: A symbol that performs an operation on one or more operands (values or variables).
  • Scope: The context in which variables and functions are accessible.
  • Server-Side JavaScript: JavaScript code that runs on a server rather than in a client’s web browser.
  • Single-Page Application (SPA): A web application that loads a single HTML page and dynamically updates the content without requiring page reloads.
  • Truthy Value: A value that evaluates to true in a Boolean context (e.g., 1, “hello”, {}).
  • Type Coercion: The automatic or implicit conversion of values from one data type to another in JavaScript.

Modern JavaScript Fundamentals

Okay, I have reviewed the provided source and have created a briefing document summarizing its main themes and key ideas.

Briefing Document: JavaScript Course Excerpts

Overview:

This document summarizes excerpts from the beginning of a “Modern JavaScript from the Beginning” course. The course aims to provide a comprehensive understanding of JavaScript fundamentals. The initial sections cover basic concepts, data types, operators, control flow, functions, scope, events and date objects as well as introduction to arrays and objects (object literals). The presenter emphasizes that even experienced developers might find value in revisiting these core principles.

Main Themes and Key Ideas:

  1. What is JavaScript?
  • JavaScript is a core technology of the web, alongside HTML (structure) and CSS (styling).
  • It brings interactivity and dynamism to web pages.
  • It can be used server-side with Node.js to interact with databases and file systems.
  • It’s an interpreted (executed line by line), high-level scripting language.
  • “JavaScript is one of the core Technologies of the web alongside HTML which is a mock-up language and is used to structure web page content as well as CSS which is used to style that content so JavaScript is what brings life to the front end or the user interface of a website or a web app”
  1. Uses of JavaScript (Client-Side & Server-Side):
  • DOM Manipulation: Dynamically changing the structure, content, and styles of HTML elements. The DOM is viewed as a tree-like structure of nodes.
  • “JavaScript provides methods for dynamically changing that structure or changing the content or the styles of the elements in the Dom”
  • Event Handling: Responding to user actions like mouse clicks, keyboard input, and form submissions.
  • “…JavaScript gives us a way to handle events so we can respond to things like Mouse clicks or drags or hovers keyboard events form submissions and just about anything you can think of that you can do in the browser window”
  • Asynchronous Requests: Interacting with back-end servers and APIs to fetch or submit data without page reloads. Common in Single Page Applications (SPAs).
  • “making asynchronous request is one of the most powerful uses of JavaScript and it’s used to interact with back-end servers”
  • Animations & Effects: Creating visual effects using CSS transitions, JavaScript methods, and libraries.
  • Data Manipulation: Sorting, filtering, and transforming data using array methods (map, filter, reduce).
  • “…data manipulation which is the process of modifying or transforming data can be done with JavaScript because it’s a full-featured language with data structures like arrays”
  • Data Storage: Storing data in the browser using local storage, session storage, and cookies.
  • Single Page Applications (SPAs): Building applications that load a single HTML page and dynamically update content. Often used with front-end frameworks (React, Vue, Angular).
  • “JavaScript can also be used to store data on the client or in the browser using things like local storage session storage and cookies we can also create single page applications or spas and these are applications that load a single HTML page and dynamically update the content without having to reload the entire page”
  • Server-Side (Node.js/Deno): Creating APIs that interact with databases. Frameworks like Express.js are mentioned.
  1. Why Learn JavaScript?
  • Popularity: Widely used language with a large community, making it a valuable skill for job opportunities and collaboration.
  • “popularity JavaScript is one of the most widely used programming languages with millions of developers using it to build websites web applications browser-based games server-side apis and more”
  • Versatility: Can be used for a wide range of applications.
  1. Data Types and Type Conversion/Coercion:
  • JavaScript has data types like numbers, strings, and Booleans.
  • Type Conversion: Explicitly changing a data type using constructors (e.g., String(), Number(), Boolean()) or methods like parseInt() and parseFloat().
  • “…if you have a decimal right so if let’s say this is amount is 99.5 and you want to let’s say it’s a string of 99.5 and you want to convert it to a number of 99.5 which is a decimal there’s a method you can use called parse float”
  • Truthy and Falsy values: Discusses truthy and falsy values. Zero is a falsy value.
  • NaN (Not a Number): Results from operations that cannot produce a valid number (e.g., parsing a non-numeric string). It is a special number type.
  • “…we get a value of Nan or Nan and what this stands for is not a number okay it’s uh it’s actually a special number as you can see it does have the type of number but it’s a special number that represents not a number”
  • Type Coercion: Implicit conversion of data types during operations, often when using operators with different types.
  1. Operators:
  • Arithmetic Operators: +, -, *, /, % (modulus), ** (exponentiation).
  • Concatenation Operator: + (used to join strings).
  • “the concatenate operator is the plus sign so you can essentially think of the plus sign having two different functions in JavaScript one obviously is addition but one is to concatenate strings together”
  • Increment/Decrement Operators: ++, –.
  • Assignment Operators: =, +=, -=, *=, /=, %=, **=.
  • Comparison Operators: == (equal to), === (equal value and type), != (not equal to), !== (not equal value or type), >, <, >=, <=. The presenter recommends using === and !== to avoid potential issues.
  • “what I do and what I’ve what I see a lot of people do is pretty much always use the triple equals I think that that’s going to save you some headaches and save you some hours if you just always use triple equals”
  1. String Methods & Properties:
  • Strings are primitive, but JavaScript provides a wrapper object allowing the use of methods and properties.
  • length: Property to get the string’s length.
  • Accessing Characters: Using bracket notation (e.g., str[0]) or charAt().
  • “…if I say x equals and then S I can use this syntax and it starts at zero just like an array if I save that you’ll see I get H I get the first character if I do one I get e so I get the second character and so on”
  • toUpperCase(), toLowerCase(): Changing case.
  • indexOf(): Finding the index of a character or substring.
  • “if we want to know the index of a specific character so kind of the the inverse of this we could say s equal x equals s and we can use index of”
  • substring(), slice(): Extracting portions of a string. Slice can use negative indices to start from the end.
  • “substring which will search a string for a specified value so let me show you if we do s dot and then substring and then we can this will take in two indexes so let’s say we want to get from 0 to 4”
  • trim(): Removing whitespace from the beginning and end of a string.
  • “trim and what this does is it trims the white space”
  • replace(): Replacing a substring with another string.
  • includes(): Checking if a string contains a substring (returns true or false).
  • “…if I say s dot includes and we want to let’s say we want to find hello if I save that we’re going to get true because this is found within that s string”
  • valueOf(): Returns the primitive value of a String object.
  • split(): Splitting a string into an array based on a separator.
  • “split which you I use I’ve used quite a bit it’ll split a string into an array and it takes in a separator as an argument”
  • Prototype: Where the methods are stored.
  1. Number Methods and Properties
  • toString(): Returns a string representation of a number.
  • toFixed(digits): Formats a number using fixed-point notation, rounding to the specified number of digits after the decimal point. Returns a string.
  • toPrecision(precision): Formats a number to a specified length.
  • toExponential(fractionDigits): Returns a string representing the number in exponential notation.
  • toLocaleString(): Returns a language-sensitive representation of the number.
  • Number.MAX_VALUE: The maximum numeric value representable in JavaScript.
  • Number.MIN_VALUE: The smallest positive numeric value representable in JavaScript.
  1. Math Object:
  • Built-in object for mathematical operations.
  • Math.sqrt(): Square root.
  • “…we want to get the the um the square root of a number so we’ll do math Dot and then sqrt”
  • Math.abs(): Absolute value.
  • Math.round(): Rounds to the nearest integer.
  • Math.ceil(): Rounds up to the nearest integer.
  • Math.floor(): Rounds down to the nearest integer.
  • “…we can do the opposite and round down with the floor method so if I were to do math dot floor obviously that’s going to give me 4 but if I even if I do like 4.9 and I save that’s still going to give me 4”
  • Math.pow(): Raises a number to a power.
  • Math.min(), Math.max(): Finds the minimum or maximum of a set of numbers.
  • Math.random(): Generates a random decimal number between 0 (inclusive) and 1 (exclusive). Demonstrates how to generate random numbers within a specific range.
  • “a really common method is the random method so let’s say x equals math Dot random”
  1. Date Objects:
  • Creating date objects: using new Date().
  • Date formats: Demonstrates creating dates with arguments (year, month, day, hour, minute, second) and with date strings. Notes a potential time zone issue when using hyphens and year-first format.
  • “…if I do a string so quotes here 20 21 let’s say Dash zero seven and let’s say 10. if I save that then we’re going to get July”
  • Timestamps: Discusses Unix timestamps (milliseconds since January 1, 1970). Date.now() gets the current timestamp. getTime() or valueOf() gets the timestamp of a specific date.
  • “…what it is it’s an integer that represents the number of seconds that’s elapsed that’s passed since the date of January 1st 1970 which is an arbitrary date”
  • “…you can always get the time stamp by using let’s say d so by using date dot now like that so if I save that we’re going to get the milliseconds that have passed if I reload you’ll see it’ll just keep updating right so that that gives you a way to always be able to mark an exact you know millisecond in time”
  • Methods for getting parts of a date: getFullYear(), getMonth(), getDate(), getDay(), getHours(), getMinutes(), getSeconds(), getMilliseconds(). Month is zero-based.
  • “if you want to get specific parts of the date we can do that so let’s say we want to get the the year so we’ll do D dot and then there’s a get full year method and you can see it gives us 2022”
  • toLocaleDateString(), toLocaleString(): More modern and powerful ways to format dates in a locale-sensitive way.
  1. Arrays and Objects
  • Section introduction: Will cover creating, manipulating and nesting arrays and objects.
  1. Scope
  • Global Scope, Function Scope, Block Scope
  • Variable Shadowing – when a variable in a local scope has the same name as a variable in the outer scope.
  • VAR is function scoped, not block level scoped.
  • Variables declared with VAR are added to the window object. Variables declared with LET and CONST are not.
  • “…when we create a global variable with VAR if we look at the window object let’s take a look here you’ll see that it actually gets added to the window object when we use letter cons that does not get added to the window object so you can see here there’s no Foo”
  • Nested Functions – child functions can access parent variables.
  1. Functions
  • Function Declaration – start with the function keyword
  • Function Expression – function assigned to a variable
  • Arrow Functions – shorter syntax for writing functions
  • IIFE (Immediately Invoked Function Expression) – function that runs as soon as it is defined.
  1. Logic and Control Flow
  • IF statements
  • IF ELSE statements
  • Truthy and Falsy values
  • Logical Operators
  • SWITCH statements
  • TERNARY Operator
  1. Events
  • Adding event listeners
  • MOUSE Events
  • KEYBOARD Events
  • Different keyboard properties to detect key presses and states

Challenges:

  • Capitalize Challenge: Capitalize the first letter of a single-word string.
  • Min Max Challenge: Create a function that takes an array of numbers and returns an object with the minimum and maximum values.
  • IIFE Challenge: Create an IIFE that takes in the length and width of a rectangle and logs its area to the console.
  • Random Number and Math Challenge: Create random numbers and calculate their sum, difference, product, quotient, and remainder, then log the results in a specific format.

Overall Impression:

The course excerpts promise a solid foundation in JavaScript, starting with fundamental concepts and progressing towards more practical applications. The instructor emphasizes understanding the “why” behind the code, not just the “how,” and provides a blend of explanations, examples, and challenges to reinforce learning.

JavaScript Fundamentals and Usage Guide

### What is JavaScript and what is it used for?

JavaScript is a high-level, interpreted programming language that is one of the core technologies of the web, alongside HTML and CSS. It is primarily used to add interactivity and dynamic behavior to websites. It can also be used on the server-side with Node.js and Deno to interact with databases and the file system. Some general uses include manipulating the DOM, handling events, making asynchronous requests, creating animations and effects, data manipulation, storing data, and building SPAs.

### What is the DOM (Document Object Model) and how does JavaScript interact with it?

The DOM is a tree-like structure of nodes representing the HTML elements on a webpage. JavaScript allows developers to dynamically change the structure, content, and styles of elements in the DOM. This includes adding, removing, or modifying text, content, and styles (like color, font, and size). Manipulating the DOM is a fundamental aspect of creating dynamic and interactive web pages.

### How can I convert data types in Javascript?

JavaScript has constructors that allow you to convert values to specific data types. The `String()` constructor converts a value to a string, `parseFloat()` converts a string to a decimal number, and `Boolean()` converts a number to a Boolean value (true or false). Zero is falsy, and one is truthy. Converting a non-numeric string using `parseFloat()` will result in “NaN” (Not a Number).

### What are operators in JavaScript and what are some common types?

Operators are symbols that perform specific operations in JavaScript expressions. Common types include:

* **Arithmetic Operators:** `+` (addition), `-` (subtraction), `*` (multiplication), `/` (division), `%` (modulus – remainder), `**` (exponentiation), `++` (increment), `–` (decrement).

* **Assignment Operators:** `=`, `+=`, `-=`, `*=`, `/=`, `%=`, `**=`.

* **Comparison Operators:** `==` (equal to), `===` (equal value and type), `!=` (not equal to), `!==` (not equal value or type), `>` (greater than), `<` (less than), `>=` (greater than or equal to), `<=` (less than or equal to).

* **Logical Operators:** `&&` (AND), `||` (OR), `!` (NOT)

### What is type coercion in JavaScript?

Type coercion is the automatic or implicit conversion of values from one data type to another in JavaScript. It typically occurs when operators are applied to values of different types. For example, when adding a number to a string, JavaScript might convert the number to a string before concatenating them.

### How do I find the length of a string?

Strings have a length property. `string.length` will produce the length of the string.

### What are some methods available on strings in Javascript?

Strings have a prototype where methods are stored. Strings have methods for changing case (`toUpperCase()`, `toLowerCase()`), finding characters by index (`charAt()`), finding the index of a character (`indexOf()`), extracting portions of a string (`substring()`, `slice()`), removing whitespace (`trim()`), replacing substrings (`replace()`), checking for inclusion (`includes()`), and splitting a string into an array (`split()`).

### How can I generate a random number in JavaScript?

The `Math.random()` method returns a random decimal number between 0 (inclusive) and 1 (exclusive). To generate a random number within a specific range, you can multiply `Math.random()` by the range and then use `Math.floor()` to round down to the nearest whole number.

“`javascript

let randomNumber = Math.floor(Math.random() * 10) + 1; // Generates a random number between 1 and 10

JavaScript Console: A Developer’s Tool

The JavaScript console is a tool available in web browsers that allows developers to log information, debug code, and execute JavaScript commands.

Key aspects of the JavaScript console:

  • Access: Accessed through browser’s developer tools (e.g., in Chrome, More Tools -> Developer Tools). Can be directly accessed using keyboard shortcuts such as Command + Option + J on Mac.
  • Functionality:
  • Displaying Warnings and Errors: Shows warnings and errors generated by front-end JavaScript code, indicating the line number and file of origin.
  • Logging Information: Allows logging of data and messages from a script using the console object.
  • Executing JavaScript: Enables running JavaScript code directly in the console.
  • The console Object: The console object in JavaScript contains methods for interacting with the console.

Commonly used console object methods:

  • console.log(): Logs information to the console. It can output different data types like numbers (e.g., 100), strings (e.g., “Hello World”), and booleans (true or false). It is possible to log multiple values simultaneously by including them as arguments.
  • console.error(): Logs an error message to the console, often with a red background or border.
  • console.warn(): Logs a warning message to the console, typically with a yellow background.
  • console.table(): Displays data in a tabular format, useful for visualizing objects with key-value pairs.
  • console.group() / console.groupEnd(): Creates a collapsible group in the console to organize related log messages.
  • console.clear(): Clears the console. It can also be cleared using keyboard shortcuts such as command/control + L.

Additional features:

  • Styling Console Logs: CSS styles can be applied to console logs using the %c specifier, followed by the desired CSS rules as a second argument to console.log().
  • Accessibility: The console is primarily a tool for developers and is not intended for end-users of a website.

JavaScript Data Types: A Comprehensive Guide

In JavaScript, data types define the kind of values that can be stored and manipulated within a program. JavaScript is a dynamically typed language, meaning that you do not have to explicitly define the data types of variables.

There are two main categories of data types in JavaScript: primitive types and reference types (or objects).

Primitive Data Types:

  • Primitive types are immutable, meaning their values cannot be changed after creation. When a primitive type is assigned to a variable, the variable is given a direct copy of the value. These values are stored directly in the memory location known as the stack.
  • JavaScript has seven primitive data types.
  • String: Represents textual data and is a sequence of characters enclosed in single or double quotes (e.g., “Hello, World!”).
  • Number: Represents numeric values, including integers and floating-point numbers (e.g., 30, 98.9). There is no distinct type for integers or decimals; all numbers are of the Number type.
  • Boolean: Represents a logical value that can be either true or false.
  • Null: Represents the intentional absence of any object value. It indicates that a variable has been intentionally set to “no value.” Confusingly, the typeof operator returns “object” for null, which is considered a historical artifact or mistake in JavaScript.
  • Undefined: Represents a variable that has been declared but has not been assigned a value. The type of such a variable is also undefined.
  • Symbol: Represents a unique and immutable value, often used as object properties.
  • BigInt: Represents integers of arbitrary precision, allowing for the storage and manipulation of numbers larger than the Number type can handle.

Reference Data Types (Objects):

  • Reference types are mutable, and when a reference type is assigned to a variable, the variable is given a reference to that value. These values are stored in the heap.
  • Objects are collections of key-value pairs. Object literals, arrays, and functions are examples of reference types.
  • Object Literal: A basic object in JavaScript, containing properties defined as key-value pairs, enclosed in curly braces {}.
  • Array: An ordered list of values.
  • Function: A callable object that executes a block of code. Functions are also considered objects in JavaScript, with the type of operator returning “function”.

Type Detection:

  • The typeof operator can be used to determine the type of a variable. For example, typeof firstName will return “string” if firstName holds a string value. However, typeof null returns “object” due to historical reasons.

Dynamic Typing:

  • JavaScript is a dynamically typed language, meaning that variable types are not explicitly defined and can change during runtime.
  • Type Conversion: It is possible to explicitly convert a value from one type to another. For instance, converting a string to a number using parseInt() or the unary plus operator (+).
  • Type Coercion: JavaScript can also implicitly change types during operations. For example, when adding a number and a string, JavaScript may coerce the number into a string.

Understanding data types is crucial for writing correct and efficient JavaScript code. Knowing the differences between primitive and reference types, how they are stored, and how type conversions occur helps in avoiding common pitfalls and writing robust applications.

JavaScript Variable Declaration Guide

In JavaScript, declaring a variable means creating a named storage location in memory that can hold a value. When declaring variables, there are three keywords that can be used: var, let, and const.

Here’s a breakdown of variable declaration in JavaScript:

  • Keywords:
  • var: The original keyword for variable declaration.
  • let: Introduced in ECMAScript 2015 (ES6), it is used for block-scoped variable declarations.
  • const: Also introduced in ES6, it is used for declaring constants, which are variables whose values cannot be reassigned after initialization.
  • Scope:
  • Global Scope: Variables declared outside of any function or block have global scope.
  • Function Scope: Variables declared with var inside a function have function scope. They are accessible only within that function.
  • Block Scope: Variables declared with let or const inside a block (e.g., within an if statement or a loop) have block scope. They are accessible only within that block.
  • Basic Syntax:
  • To declare a variable, you use one of the keywords (var, let, or const) followed by the variable name. For example:
  • var firstName;
  • let age;
  • const PI = 3.14159;
  • Initialization:
  • Variables can be initialized at the time of declaration by assigning them an initial value using the assignment operator (=).
  • let firstName = “John”;
  • const age = 30;
  • Variables declared with let can be declared without immediate initialization.
  • Constants (const):
  • Variables declared with const must be initialized during declaration.
  • const GRAVITY = 9.8; // Correct
  • // const E; // Error: Missing initializer in const declaration
  • Constants cannot be reassigned after initialization.
  • const PI = 3.14;
  • // PI = 3.14159; // Error: Assignment to constant variable.
  • It is possible to modify the properties of an object or array declared with const, but it is not possible to reassign the variable itself.
  • const myArray =;
  • myArray.push(4); // Valid: myArray is now
  • const person = { name: “John” };
  • person.name = “Jane”; // Valid: person.name is now “Jane”
  • // myArray =; // Invalid: Reassignment of const variable
  • Naming Conventions:
  • Variable names can contain letters, numbers, underscores, and dollar signs.
  • Variable names cannot start with a number.
  • JavaScript uses camel case as a common convention for variable names (e.g., firstName, lastName).
  • Hoisting:
  • Variables declared with var are hoisted to the top of their scope, meaning they can be used before they are declared in the code. However, they are initialized with undefined until the line where they are assigned a value.
  • Variables declared with let and const are also hoisted, but they are not initialized. Using them before their declaration results in a ReferenceError.
  • Multiple Declarations:
  • It is possible to declare multiple variables in a single statement.
  • let a, b, c;
  • const x = 10, y = 20, z = 30;
  • However, it is generally recommended to declare each variable on a separate line for better readability.

JavaScript Object Literals: Comprehensive Guide

Object literals are a fundamental concept in JavaScript used to create objects, which are collections of key-value pairs. They are a primary way to define objects in JavaScript.

Here’s a detailed discussion of object literals, drawing from the sources:

  • Definition: An object literal is a way to create a new object in JavaScript using a simple, concise notation. It involves defining properties (key-value pairs) within curly braces {}.
  • Syntax:
  • An object literal consists of key-value pairs, where keys are strings (or symbols) and values can be any data type, including primitive values, other objects, or functions.
  • Keys and values are separated by a colon :, and each key-value pair is separated by a comma ,.
  • Example:
  • const person = {
  • firstName: “Brad”,
  • age: 40
  • };
  • In this example, person is an object with two properties: firstName with the value “Brad”, and age with the value 40.
  • Properties and Methods:
  • Properties are the key-value pairs that store data within the object.
  • Methods are functions that are associated with an object and can be called using dot notation.
  • Accessing Properties:
  • Properties of an object can be accessed using dot notation (objectName.propertyName) or bracket notation (objectName[“propertyName”]).
  • console.log(person.firstName); // Output: Brad
  • console.log(person[“age”]); // Output: 40
  • Nesting Objects:
  • Objects can be nested within other objects, allowing for complex data structures.
  • const person = {
  • name: “Brad”,
  • address: {
  • street: “123 Main St”,
  • city: “Anytown”
  • }
  • };
  • console.log(person.address.city); // Output: Anytown
  • Adding or Changing Properties:
  • Properties can be added to an object or their values modified after the object has been created using dot or bracket notation.
  • person.email = “brad@example.com”; // Adding a new property
  • person.age = 41; // Modifying an existing property
  • Using Functions as Methods:
  • Functions can be added as methods to object literals. The this keyword can be used within a method to access other properties of the object.
  • const person = {
  • name: “Jane Doe”,
  • greet: function() {
  • console.log(`Hello, my name is ${this.name}`);
  • }
  • };
  • person.greet(); // Output: Hello, my name is Jane Doe
  • Object Constructor:
  • Another way (besides object literals) to create objects is to use the object constructor.
  • let todo = new object ();
  • This creates an empty object to which properties can be added with dot notation such as todo.id = 1;
  • Enhanced Object Literals (ES6):
  • ES6 introduced several enhancements to object literals, including shorthand property names and computed property names.
  • Shorthand Property Names: If the property name is the same as the variable name, you can use a shorthand notation.
  • const firstName = “John”;
  • const age = 30;
  • const person = {
  • firstName, // Shorthand for firstName: firstName
  • age // Shorthand for age: age
  • };
  • Spread Operator:
  • The spread operator (…) can be used to copy properties from one or more objects into another object.
  • const obj1 = { a: 1, b: 2 };
  • const obj2 = { c: 3, d: 4 };
  • const obj3 = { …obj1, …obj2 };
  • console.log(obj3); // Output: { a: 1, b: 2, c: 3, d: 4 }
  • Object.assign():
  • The Object.assign() method is another way to merge the properties of one or more source objects into a target object. The first argument is the target object, and subsequent arguments are the source objects.
  • const obj1 = { a: 1, b: 2 };
  • const obj2 = { c: 3, d: 4 };
  • const obj4 = Object.assign({ }, obj1, obj2);
  • console.log(obj4); // Output: { a: 1, b: 2, c: 3, d: 4 }
  • Object.keys(), Object.values(), and Object.entries():
  • Object.keys(): Returns an array of the object’s property names (keys).
  • Object.values(): Returns an array of the object’s property values.
  • Object.entries(): Returns an array of the object’s key-value pairs as arrays.
  • const person = { name: “John”, age: 30 };
  • console.log(Object.keys(person)); // Output: [“name”, “age”]
  • console.log(Object.values(person)); // Output: [“John”, 30]
  • console.log(Object.entries(person)); // Output: [[“name”, “John”], [“age”, 30]]
  • hasOwnProperty():
  • The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (not inherited).
  • const person = { name: “John” };
  • console.log(person.hasOwnProperty(“name”)); // Output: true
  • console.log(person.hasOwnProperty(“age”)); // Output: false

Understanding object literals and how to manipulate objects is crucial for effective JavaScript programming. Object literals provide a flexible and readable way to create and work with complex data structures.

JavaScript Array Methods: A Comprehensive Guide

Arrays in JavaScript are special types of objects that are a data structure used to store multiple values. Array methods are built-in functions that can be used to manipulate arrays. There are many different array methods, but some of the most common and useful ones include push, pop, shift, unshift, slice, splice, concat, forEach, filter, map, and reduce.

Here’s a discussion of array methods, drawing from the sources:

  • Creating Arrays:
  • Array Literal: An array can be created using bracket notation with values inside the brackets, such as =.
  • Array Constructor: An array can also be created using the array constructor by calling new array().
  • Basic Array Methods:
  • push(): Adds one or more elements to the end of an array. Modifies the original array.
  • pop(): Removes the last element from an array and returns that element. Modifies the original array.
  • shift(): Removes the first element from an array and returns that element. Modifies the original array.
  • unshift(): Adds one or more elements to the beginning of an array. Modifies the original array.
  • reverse(): Reverses the order of the elements in an array. Modifies the original array.
  • Methods to get information from an array:
  • includes(): Determines whether an array includes a certain value among its elements, returning true or false as appropriate.
  • indexOf(): Returns the first index at which a given element can be found in the array, or -1 if it is not present.
  • Methods to extract a section of an array:
  • slice(): Returns a new array containing a portion of the original array. Takes two arguments: the starting index and the ending index (exclusive). The original array is not modified.
  • splice(): Changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. Takes two arguments: the starting index and the number of elements to remove. The original array is modified.
  • Methods to combine arrays
  • concat(): Returns a new array that is the result of merging two or more arrays. The original arrays are not modified.
  • Spread Operator: The spread operator (…) can also be used to concatenate arrays.
  • It can extract the items from both arrays and combine them.
  • Methods for looping through arrays:
  • forEach(): Executes a provided function once for each array element.
  • It does not create a new array or modify the original array.
  • It’s used to simply iterate through the array and perform an operation on each element.
  • High Order Array Methods:
  • These methods take a function as an argument (a callback function) and can be used to iterate through arrays and perform specific operations on each element.
  • filter(): Creates a new array with all elements that pass the test implemented by the provided function.
  • It returns a new array containing only the elements that satisfy the provided condition.
  • map(): Creates a new array with the results of calling a provided function on every element in the calling array.
  • It transforms each element of the array according to the provided function.
  • reduce(): Executes a reducer function (that you provide) on each element of the array, resulting in single output value.
  • It reduces the array to a single value by applying a function that accumulates the result.
  • It takes two arguments: an accumulator (previous value) and a current value.
  • Methods to flatten arrays:
  • flat(): Creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
  • It flattens nested arrays into a single array.
  • Static Methods on Array Object:
  • Array.isArray(): Determines whether the passed value is an array.
  • Array.from(): Creates a new array from an array-like or iterable object.
  • Array.of(): Creates a new array from a set of arguments.

It is worth noting that some array methods modify the original array, while others create and return a new array. It is important to be aware of this distinction when using array methods, as it can affect the behavior of your code.

Modern JavaScript From The Beginning | First 12 Hours

The Original Text

hey what’s going on guys so I know you haven’t seen much of me lately I’ve been just really busy between my personal life and also working on courses and ideas for travestymedia.com which is my biggest Focus right now and I will be making videos soon but I wanted to give you guys kind of a little treat so this is the first 13 hours of my modern JavaScript from the beginning course which is a 37 hour course so it is only a portion but it’s packed with fundamentals and we go pretty deep into those fundamentals so things like data types control structures functions Loops the Dom so I really hope you enjoy it and if you do want to go further and you want to watch the other 20 plus hours I will have a link to the course in the description uh with a promo code so obviously this is geared more towards beginners but even if you’re already a JavaScript developer I can guarantee you that there’s there’s something you’ll learn all right so let’s get into it [Music] all right guys so I just want to quickly go over what JavaScript is and why you should use it so JavaScript is essentially the Java programming language as the name implies I’m kidding JavaScript has nothing to do with Java other than they share a similar name and they’re both programming languages so JavaScript is one of the core Technologies of the web alongside HTML which is a mock-up language and is used to structure web page content as well as CSS which is used to style that content so JavaScript is what brings life to the front end or the user interface of a website or a web app and it allows us to make web pages Dynamic not only that but it can also be used on the server side to do things like interact with databases and work with the file system and this is with the help of the node.js runtime so JavaScript is a high level interpreted programming language used to create interactive and dynamic website experiences and when I say interpreted what I mean is that it’s executed line by line rather than being compiled into machine code first so the code is executed on the Fly making it a scripting language hence the name JavaScript so as far as what JavaScript is used for I wouldn’t be able to fit everything on this page so I’m going to go over just the general things that JavaScript is used for so first off it’s used to manipulate the Dom or the document object model and I’ll be going over the Dom in depth but you can basically think of it as a tree-like structure of nodes and everything on the page is a node including every HTML tag every attribute every piece of text and so on so JavaScript provides methods for dynamically changing that structure or changing the content or the styles of the elements in the Dom for example you can use JavaScript to add remove or change text of a heading or the content of a div or the styles of an element such as its color font and size so this is an important aspect of JavaScript as it allows developers to create Dynamic and interactive web pages that can respond to user actions now those user actions are called events and JavaScript gives us a way to handle events so we can respond to things like Mouse clicks or drags or hovers keyboard events form submissions and just about anything you can think of that you can do in the browser window and again this allows us to create very Dynamic interfaces and things like modals or drop downs collapsible content and so on so making asynchronous request is one of the most powerful uses of JavaScript and it’s used to interact with back-end servers whether it’s your own server that you created or a public API such as the GitHub or YouTube API so we can make HTTP requests right from our code to fetch data or submit data and this happens all behind the scenes without having to refresh the page and this is often used in what are called single page applications or Spas to dynamically load and update content without having to reload the entire page so as far as animations and effects there’s many different ways that we can create these using JavaScript we can use CSS Transitions and animations with JavaScript there’s the request animation frame method there’s different libraries like animate.css and gsap so these methods allow developers to create a wide range a wide range of animations such as fading moving elements along a path scaling rotating and so on now data manipulation which is the process of modifying or transforming data can be done with JavaScript because it’s a full-featured language with data structures like arrays and this allows us to sort filter and aggregate data so there’s all kinds of powerful array methods that we can use such as map filter reduce and we’re going to get into all of these later on so JavaScript can also be used to store data on the client or in the browser using things like local storage session storage and cookies we can also create single page applications or spas and these are applications that load a single HTML page and dynamically update the content without having to reload the entire page and this provides a really seamless and responsive user experience so no page reloading we can create different routes and so on and usually you would use a front-end framework for building Spas so you’d use something like react or view or angular but you can also create them with vanilla JavaScript now everything that I’ve said up until this point is all client-side or front-end JavaScript and that’s where it is used the most I would say but you can also use it on the server side with the node.js runtime as well as Dino so in addition to consuming apis from the front end we can also create apis that interact with databases on the back end and there’s a ton of Frameworks that you can use to help you with this including Express which is extremely popular and we’ll actually be creating a backend API with Express later on so the last thing I want to go over are some reasons why you should learn JavaScript so one is popularity JavaScript is one of the most widely used programming languages with millions of developers using it to build websites web applications browser-based games server-side apis and more so it makes it a very valuable skill to have and it opens up many job opportunities and allows for collaboration with other Developers so it’s also very versatile um it’s used like I said on both on the front end and back end of web development making it a full stack language this versatility allows developers to build complete web applications using only JavaScript not only that but there’s Technologies like react native which allow you to build complex mobile applications and Technologies like electron which allow you to even create desktop applications some of the most popular desktop apps are actually built on JavaScript and electron including vs code which is the text editor that we’ll be using as well as Postman which is the HTTP client that we’ll be using so I would say that JavaScript is relatively easy relative being the key term so if you compare it to other languages especially more low-level compile languages like C and C plus plus it’s much easier to get into and I think anyone who has a passion for coding can learn JavaScript and you don’t have to be some genius you don’t have to be great at math or anything like that you just have to have some drive and the willingness to learn and put the effort in so JavaScript also has a very very large and active Community which provides a wealth of resources support tutorials and tools for Learning and improving your skills from websites like stack Overflow to social media JavaScript just has a huge reach and when it comes to tools like actual development tools there’s just there’s so much open source software so you have npm which is the node package manager with I think it’s like 1.3 million packages that you can just download install and use so there’s just there’s there’s no shortage of resources or tools when it comes to JavaScript all right guys so in this video I want to go over the tools we’ll be using as well as our environment which is going to be very simple we’re writing vanilla front-end JavaScript so essentially all you need is a text editor and a browser but I do want to show you some of the extensions that I’ll be using and so on so as far as a text editor you can use whatever you want you probably already have a preference I’m going to be using visual studio code that’s what I recommend it’s very easy to use it’s intuitive it has great extensions and it’s very popular I would say the most popular for web development especially front-end web development and then there’s some extensions I’ll be using as well so I would suggest using it but you don’t have to if you use Sublime Text or atom or something else you can still follow along just fine so the next thing I’d say to install is git if you don’t have that already and git is Version Control so basically we can create repositories with our code and we can also push to third-party services like GitHub or git lab or bitbucket so this is not a git course but I will show you just the basics and we will need to push to a a service so that we can host some of our applications some of our projects because I do want to do a couple simple deployments all right and you can install get many different ways if you’re on Mac you can use Homebrew you can also go to get Dash scm.com and you can download and install it as well and then I’d also say install node.js just to have it on your system node.js is a it’s a JavaScript runtime so it essentially allows you to run JavaScript on your machine or on a server rather than just in the browser so you can actually use node.js as your your backend technology now this of course is not a node.js course but there are some things that I’d like to talk about especially with npm which is the node package manager and that comes with node.js so I would suggest installing that and you can install either the long-term support or the cut the most recent the the current version really doesn’t matter for this course so what I want to do now is just go into vs code and just show you the extensions that I’m using now I have a ton installed but the there’s really only two that I would highly recommend that you use with this course so one is called live server so if we scroll down here see right here live server so we we are we’re writing front-end JavaScript so we don’t really need any kind of server you could have an HTML file right on your desktop and have a Javascript file linked to it or just create the script tag in the HTML file and just open it run it in a browser and it works however live server gives you like a mini Dev server that you can run your uh your files with and it’ll Auto reload in the browser whenever you make any changes and that that includes making changes in the JavaScript the HTML the CSS if you change any of that code it auto reloads so you don’t have to keep reloading the browser yourself so I would definitely recommend using this that’s what I’ll be using throughout the course and then the other thing that I would suggest is prettier which is a code formatter it just keeps your your code nice and clean in fact I’m going to bring over a file real quick and you guys of course don’t have to do this but I’m just going to open this up it’s a file from from the course and I’m going to show you my settings in a minute but basically you’ll see if I tab a line way over here and then I go when I save it’ll put it right back okay so it keeps your your code nice and clean and then you can also set like the the spacing you can set if you want to use semicolons or not because in JavaScript semicolons actually are not you know they’re not mandatory so you can set those to on or off as you can see I have them set to on so if I miss a semicolon and I save it adds it automatically and you can also set it the other way around where if you have a semicolon and you save it gets rid of it and then the other thing that I want to show you are quotes so you can see this string is wrapped in single quotes I prefer to use single quotes so I have it set so that if I do if I have double quotes in here and then I save it automatically gets set to single quotes all right now where you can configure this stuff once you install prettier is if you go to the settings so right here settings and then just search for prettier and then you’ll find all these these options here but the ones I want to show you are right here so semi you can see I have this checked so it’s going to add semicolons if I forget if I uncheck it it’ll do the opposite and then down here I have single quote checked which by default I believe this is not checked but I prefer a single quotes So I do have it selected and then here my tab width I believe the default is four but I have mine set to two which makes it a little more Compact and neater in my opinion all right so those are the settings now to make sure that your code formats when you save just search for a format in the settings and right here format on Save just make sure that that’s checked all right so we can close that up close that but that’s it as far as the tools that I’m using and our environment so let’s move on to the next video okay so most of the code that we write is going to be within a JavaScript sandbox which is just a bunch of files and folders that are going to pertain to each section of the course but before we do that I just want to show you the very basics of just creating an HTML and a Javascript file and running the JavaScript in the browser Etc and for those of you that you know aren’t are pure beginners just kind of bear with me because I do want this course to be for everybody even if they’re just just starting out with JavaScript so you can skip some of these videos if you want or just you know watch them as a refresher so I’m just going to create a folder so go ahead and create a folder wherever you want I’m going to create it on my desktop and I’m just going to call it I’ll call it my Dash website again I’m going to delete this after so it doesn’t matter now you want to open the folder with your text editor and there’s multiple ways to do that you can open the text editor and you can open the folder from there or you can usually on Windows you can usually right click and if you’re using vs code you’ll see an option to open with code so you can go ahead and do that if you’re using Sublime text you I think you also have a context item if you’re on a Mac what you can do is drag the folder down to the vs code icon or whatever you’re using and it will open it up and you can see on the side here is our my website site folder so from here I’m going to create a new file just click this icon and let’s say index.html so now we have an HTML file and with vs code we have a tool called emit which is really great for for writing quick HTML and CSS so for instance I could do H1 enter gives me an H1 tag if I want to add a class I could say like my class so dot my class enter or Tab and then if I wanted an ID I could do you know my ID enter our Tab and let’s say I wanted like five each ones I could do times five there’s all types of stuff you can do so I do have a YouTube video on Emmett if you’re interested but another thing emit allows us to do is just create a kind of a boilerplate for our HTML so I’m just going to hit exclamation enter and you can see it gives us our head body tags Etc and again if I know a lot of you guys already know this most of you probably do but just bear with me so if I just hit tab a couple times I can go to the title and just change it to let’s say my website and then in the body for now I’m just going to put in H1 and then hello world and save that okay now since this is an HTML file I can just open it like I can just click on it make sure it opens with a browser and we’ll be able to see the hello world so you can just develop like this if you want for this course like I’m just going to make this smaller so if we change something like let’s say we put an exclamation here and I save obviously since I just opened it on my file system not on any kind of server I go over here and I have to reload now I don’t want to have to do that for everything so that’s where live server comes in so what we can do as long as you have it installed just search for live server so right here and get that installed and then you’ll see this go live button down here you could click that or you could right click and just say open with live server and what it’ll do is open up another Tab and you can see in the URL bar it’s this is our Local Host this is one two seven zero zero one that’s called our loopback address and it runs on Port 5500 by default now if I were to change something like let’s say get rid of this exclamation and save you’ll see it auto updates or Auto reloads in the browser so I don’t have to keep reloading and that and that is with HTML CSS and JavaScript now I expect that you guys know HTML you should know at least the basics of CSS so I’m not going to really get into that to start to write JavaScript there’s a couple ways we can do it one it one way is not really recommended but I’m going to show you it anyway and that is to just write it directly in the HTML so to do that what you would do is go down right above the ending body tag and create a script tag which is an HTML tag and then anything we write in here is gonna is gonna run as our JavaScript so for instance we could do alert which is just it’s a function that’s on the window object and I’m going to talk about that in a little bit and we can pass in here let’s put a string so we need our quotes and again I’m going to talk about data types and all that very soon but I’m just going to do a Hello and save and you’ll see that that’s going to automatically run because we are using live server so since the file changed the website reloaded and now received seeing this alert of hello all right now typically you’re not going to do this you’re not going to write your JavaScript directly in your HTML it’s just bad practice you want to have your JavaScript separate okay this is called inline JavaScript just like with your CSS you normally wouldn’t write your CSS in your HTML you’d create a separate file so let’s create a new file and you can call it whatever I like to use script JS for just general JavaScript files and this will show us our alert again because the the page reloaded and then in here let’s write something else we’ll do an alert and let’s say hello from the JS file now if I save this we’re still just seeing the hello that’s in the index.html because we haven’t specified that we actually want this file to run so to do that we’ll come over here let’s get rid of the inline JavaScript but we’re going to keep the script tags now to load this script.js file we can just add a source attribute much like you would do with an image tag so let’s just say script.js it’s in the same folder you might have it in a JavaScript folder or JS folder like that but ours is right there so we’ll go ahead and save and now we’re going to see this hello from JS file okay so that Javascript file is now being loaded very very very simple stuff I know ninety percent of you probably already know this but of course I need to think of people of all skill levels okay so what I’m going to do now is stop live server and you can do that by hitting this button right here you can also right click and say stop live server and now if I reload this it’s not going to work anymore okay so I’m going to close vs code and I’m just going to delete this this uh my website folder and then in the next video we’re going to start to learn about the console in the browser which is extremely important and we’re going to start working on our Java in our JavaScript sandbox all right guys so before we start learning JavaScript I just want to quickly talk about the JavaScript sandbox when I do a course I don’t like to just type out the code and and that’s that I want you guys to have uh Resources with all the code in the course so what I do is create something called The Sandbox which has a folder for each section and in each section folder you have a folder for each video with that code okay so as you can see I’m just starting out here so I have my variables and data type section with the first video which is going to be about the console and then in that is just an index.html which right now is empty and a script JS which is empty okay now for the most part most of the learning modules that aren’t part of a project in the beginning are only going to need these two files so you don’t have to use the sandbox you can create your own files now in the downloads for this video you will have the finished version of the sandbox which of course is all the finished JavaScript and then you’ll have a starter version which is going to be pretty much everything but the JavaScript you’ll have all the files and folders you’ll have the HTML any CSS if we used any CSS but the JavaScript will be empty and if you want to use that starter package you can or like I said you can create your own so right now what I’m going to do in this this console folder is just create a boilerplate so I’ll just do exclamation and I’m just going to put console in the title and I’m not going to create this in every video I’m just showing you just just for the beginning and then since we’re not dealing with you know the Dom or anything yet I’ll just have an H1 in here that says oh we’ll put the name of the say console the name of the video and then we just want to add a script tag we can do script colon SRC and we want to link in our script JS okay so essentially at the beginning all of all the videos will start like this in the HTML and then we’ll proceed in our JavaScript now one thing I want to mention is if you’re creating folders like if you create a folder inside of an empty folder by default it’s going to be compact so it’s going to be like data type slash and then zero one console now I don’t like that because it can be kind of confusing which you know to know which folder you’re in so if you want to disable that you can just click on settings so we’ll go to settings microphones in my way and then just search for compact and then right here compact folders I have it unchecked but if I check it you’ll see it goes in this this horizontal fashion which I don’t like so you can just uncheck that if you want all right so now that we have this set up I’m just going to open this index.html with live server and we have our script connected so we don’t even need that HTML anymore and we’ll just make this a little smaller and now in the next video we’ll start to look at the JavaScript console all right guys in this video I want to go over the console in the browser because this is something that we’ll be using throughout the entire course and you’ll be using throughout your entire career as a front end or full stack web developer now every browser no matter which browser it is I’m using Chrome they all have what are called developer tools or Dev tools and in Chrome you can go to the menu and you can go to more tools and then developer tools or you can on Windows I believe it’s F12 you can toggle the dev tools and then on a Mac you can do command option I now you’ll see there’s a bunch of tabs here you’re probably familiar with the elements tab where you can you know highlight elements you can see the CSS you can even edit uh page elements of course this is only on my machine if I reload it goes back but you can do a lot with the elements tab but that’s for HTML CSS the console is where we’ll see all of our front-end JavaScript warnings and errors and we can log things to the console that’s what I want to get into in this video now you can also go directly to the console with command or control I think on Windows it’s can it’s Control Alt J I know on Mac it’s command option J and that will open it’ll go right to the console now as I mentioned this is where you’re going to see your your warnings and errors for example if I go into my script here and I just put in an A and I save that and it runs we’re going to see this reference error it says a is not defined shows me the line number and the file where it’s coming from all right so very helpful with con with uh warnings and errors and of course we can log to the console from our script which I’ll show you in a second but we can also type JavaScript right in here so if I wanted to do an alert I could execute that and you’ll see that well we get this alert with one now we’re going to see undefined on the next line because what this is is if there’s a result of the expression then it will be put here and there’s no result to alert we’re just running an alert function if I were to do let’s say one plus one then it’s going to show me two all right I can also set variables so let’s say I wanted to set x to the value of 100 and and we’ll go over variables and data types and all that but I can do that here as well I get undefined because nothing there’s no result to that if I were to do let’s say X plus 10 then we’re going to get 110 because X is equal to 100 okay I could use the date function if I wanted to to get the date so there’s there’s all types of stuff we can do here but you’re not going to do that very often maybe to do some testing and you know see if something is available on a Dom element or something like that but it’s not too often you’ll type JavaScript in here now to clear your console there’s a few things you can do you can use the clear function so clear with some parentheses and that’ll clear it also you can do command or control L that’ll clear it up as well or you can just reload the page all right so I’m gonna come over here into my script and I’m going to show you how we can log to the console uh in a couple different ways now we do this with the console object in fact if we go over here and we type console in the console and hit enter we’re going to see the console object now objects are common in in just about every programming language and you can think of them as they’re an entity that have properties and methods a property is like an attribute or a value where a method is a function something that does something and you can see that these are actually all methods they have an F next to them they’re functions and functions are executed with parentheses and don’t worry if you don’t understand that we’ll get into functions in a little bit now there’s quite a bit here but don’t let that overwhelm you because you’re only going to use maybe five percent of these most of the time you’re going to be using console log or console.log so let’s come over to to our script I’m actually going to reload the page just to clear that up and let’s look at console.log now what this is is console is is an object and remember an object has properties and methods a method is a function so log is the method that I’m using and to execute a function or a method you have to use parentheses so I’m executing the log method that’s on the console object and we use this dot syntax in JavaScript to access properties and methods okay now we want to log something so in here in the method or in the function we want to pass in an argument so I’m going to pass in a number let’s say 100 and if I save that and it runs you’ll see that now in the console we’re seeing 100. now any piece of data in JavaScript or really in any programming language has a type and this is the type of number and I’m going to go over the data types in the video after the next one so let’s say we want to log a different type like a string so a string is just a string of characters so a string has to be wrapped in either double quotes or single quotes so I’ll just say hello world and I’ll save that and you’ll see that will log the string and notice they’re different colors so the number is purple the string is white now if you want to log more than one thing at the same time you can do that as well so let’s say we want to log a number we’ll say 20 and then a string and then let’s say a Boolean which is a true or false so if I go ahead and save that you’ll see that it’ll log those three things those three values now in in many cases or I’d say most cases you’re going to be logging variables or results to functions it’s not that often you’ll log straight strings like that unless it’s like it worked or something if you’re running a function or something like that and you want to see if it worked so let’s just create a variable and we’ll get into variables more soon but if I just set let’s say x to the value of 100 then I can come down here and console.log x and of course that’s going to give me 100. all right now there is another extension that I I don’t think I mentioned and that is let’s see where is it right here JavaScript es6 code Snippets and it just gives you some some convenient Snippets and one of which um that I use quite a bit is CLG so if I do CLG enter it gives me a console log so I’ll use that quite a bit there’s also some other ones I use like try catch you can do if statements you know and I don’t usually use it for like if statements and stuff but you will see me do CLG and maybe a few others now in addition to log we also have console.error so I’ll say just alert and that’ll log to the console but you can see it has this red background red border and it also shows you the scope so I mean it’s up to you if you want to use it I I typically don’t I usually use console.log for everything but remember the console is for the developer this isn’t for the user users don’t come to your website and open up the console now in addition to alert we also have con console.warn so I’ll just say warning save that you’ll see we get the the yellow background pretty much the same thing just a different color and then we can also do tables for objects so I’m going to do console.table and I know we haven’t gone over objects yet but there are object literals I should say which are key value Pairs and they’re wrapped in curly braces so I’ll just do a simple object with a name as the key Brad is the value and then email as the next key and then Brad at Gmail for the value and if I save it you’ll see this object is printed out as a table which is kind of nice and it also shows it as the object next one is groups so we can do console.group and give that group a name let’s call it simple and then we can add some let’s just take we’ll just take these three here and put those right underneath and then we want to end the group so we can say console dot group end and if I save that we check it out you’ll see that we have this simple with the this this collapsible arrow and the warning the alert and the log are now under that in that group all right now this isn’t really this isn’t something that I use but I just want you guys to know that this stuff is available you’ll probably only end up using console log 95 of the time but again I do want you to know some of the stuff that that’s available on this console object now another thing that we can do that’s kind of cool you probably won’t use it much but I do want to show it to you is adding CSS styles to your console logs so what we can do is is create a variable I’ll call it Styles and I’m assuming that you guys know CSS but we can put some Styles in here like let’s say padding 10 pixels we’ll say let’s do background Dash color and we’ll do white and then let’s do the color the text color which will be green okay so we just have a variable with some CSS now what we can do is a console log and I’ll put a string in here of hello world and the way that we apply the Styles is at the beginning of the string we can add a percent C and then as a second parameter we can pass in our Styles now if I save that and run it you’ll see down here we get the string of hello world with the CSS Styles applied now there are some other methods on the console object but I don’t want to spend too much time on stuff you’re probably never going to use so in the next video we’re going to look at code commenting we’re also going to talk about some of the helpful keyboard shortcuts that you can use while writing code all right guys so in this video I want to talk about commenting and also give you some helpful shortcuts to use while you’re coding now as far as the the code here it’s the same exact stuff that we did in the last video we’re not actually going to write any code in this video aside from comments but I am going to show you how to kind of navigate around and use some keyboard shortcuts Now comments are used for documenting your code and explaining things in a more human readable way oftentimes multiple developers work on the same code base and comments are used to explain what a certain piece of code does it’s especially important when you’re working on a project with a team of developers and comments are also used to disable code so if you have code that you don’t want to delete but you also don’t want to run then you would comment that block of code out you can even use commenting as like a to-do list for for yourself or for other developers so very helpful and commenting in JavaScript is very simple so I’m just going to go up to the top here and we can just add double forward slashes and this is a single line of code so say this is a single line of code if I go on to the next line and start typing you’ll see it’s not commented all right now in vs code and in most text editors if you just hit command or control and then forward slash it’ll put the double forward slash for you you can toggle it all right also if you want to comment out a line of code that’s already there like let’s say this one you can go anywhere on the line and just hit command or control forward slash and you can toggle it you know put it into a comment and toggle it so if you want to toggle multiple lines of code there’s a few ways you can do it what I would probably do what I usually do is go to either the beginning or the end hold shift and hit up or down depending on what which code I want to highlight and then I’ll go ahead and do command or control forward slash and it will comment all those lines out but when you do that every line has a comment on it there’s another way to add multi-line comments and that’s with the forward slash and asterisk and then you want to go to wherever you want the comment to end and put an asterisk forward slash so now you can see everything that’s in between that is is commented out in fact I’m just going to put right here we’ll say multi multi-line comment okay so those those are the two ways of commenting in JavaScript now as far as keyboard shortcuts I already showed you that if you hold shift you can go up or down and you can highlight code you can also hold shift and go right or left and highlight as well if you want to navigate a line of code I’m just going to go to this one actually let’s go to this this table right here so if we go to this table and I hold down command or control and I hit right now the right arrow it’s going to go all the way over to the end of the line if I hit left it’ll go to the beginning of the line okay now if you want to go in between and you don’t want to navigate every single character you just hold option or alt on Windows and you can see it’ll go from this console to the end the beginning of console to the end if I hit right again it goes to the end of table hit right again it goes to the beginning of the object and so on okay so it’s just a faster way to navigate across now you can also hold down shift and if you do option or alt right or left it’ll just highlight it’ll go across faster and you can highlight while you’re doing that and you can also hold shift and hold down command or control and you can highlight from where you are over either right or left okay now if you want to move a line of code up or down you can hold alt on Windows or option on a Mac and you’ll see this console.table I’m just moving it up and down the file okay that’s holding option or alt if you want to duplicate it then you could hold shift option or shift alt and hit the down arrow and you’ll see I’m just copying the the line of code down and of course undo is is a command or control Z all right now let’s see if you want to let’s say I want every instance of this log right here so I’m going to hold shift and just highlight it and then in vs code it’ll automatically highlight each one now if you want to a little it’s not actually highlighting it like with your cursor it’s just visually if you want to actually highlight with your cursor I can hold I can hit command or control D and you’ll see it selects the next DOT log if I hit command or control D again it selects the next one and I can edit those I’m editing you know all of the dot all the logs okay now if you want to select all of them instead of going one by one with command or control D you can do shift what is it command shift L will will highlight them all and you’ll see now I got all the dot logs and I can edit them all right you can also place your cursor so if I want to put my cursor at the beginning of the the log here I can hold either alt on Windows or option on a Mac and I can just click there click here and click here and then I can type in all where all the cursors are okay so you’re not going to remember these right now so don’t worry you know when you move to the next video and you forget all of these don’t worry about it use use one or two you know while you’re coding even in this course use one or two and learn them so that it kind of becomes second nature and then choose another one or two and start to use that you know and before you know it you’ll you’ll just do it without even thinking all right and then a couple others I wanted to show you if you do command shift o you can search for a file so if we do like index you’ll see that both of our index htmls if I do script you can see our script js’s and you can switch to those as well all right if you want to search you can do let’s see you can do command option f and if I want to look for you know console it’ll show me all those you can also do command shift F and you can search over here for um we’ll say console and it will show us all where console is in every file not just the file that we’re in all right and you can also just click on search here as well and if in vs code if you want to toggle the sidebar you can do command B so our control B that’ll just toggle the sidebar uh what else if you want to toggle the terminal you can do command or actually it’s control till day so I can toggle the terminal down here which we’re not going to get into maybe maybe we will later on in the course but yeah so those are the kind of the the most common shortcuts that at least at least that I use so hopefully that helps and in the next video we’re going to start to look more at variables so in this video we’re going to start to look at variables and variable declarations now variables are basically containers for pieces of data and that data can be one of many different types and it’s important to understand the different data types in JavaScript so we’re going to go over that in the next video now when we declare a variable we need to use one of three keywords so let’s just say ways to declare a variable so basically we have VAR let’s make sure we comment this out so we have VAR we have let and we have const okay so these are the three ways that you’ll see variables declared in JavaScript now you probably won’t see VAR very much anymore VAR was the original declaration but in es2015 which is the 2015 update of JavaScript or ecmascript also known as es6 it was a huge update to the language and they introduced let and const and the main reason for that is due to something called scope and I’m not going to get too much into scope right now because it’ll go over a lot of people’s heads that are just getting started we’re going to have a whole section on function scope execution context and stuff like that but for now just know that when you write code in just right in the file not inside of a function not inside of an if statement that’s the global scope all right now in the global scope VAR and let work in a very similar way now const is a little different because it’s for constants it’s for values that you that are not going to be reassigned at a later time okay and I’ll get I’ll I’ll show you const in a few minutes but let’s start by just creating some variables here I’m going to say first name and let’s set that to a string so we do need quotes so we’ll say John now notice I made this n capital so the basically the beginning of the second word I capitalize I’ll talk about that and some other ways you can format your variables in a few minutes but let’s say first name we’ll say last name and set that to do okay so we’re just creating some strings putting them into some variables and we’ll do a console log of first name and we can log more than one thing so we’ll do that here as well and you’ll see we get John Doe okay and if I wanted to create a variable with another data type like a number we could say let age equals 30. we can console log age okay now if I try to log age up here you’ll see that I’m going to get an error it says cannot access age before initialization when we do this right here let cons VAR this is initializing a variable okay and you want to initialize it before you use it now it does act a little different if we use VAR so if I say VAR here and I run this we don’t get an error but you’ll see that it is undefined and this is due to something called hoisting which is a little more advanced and we’ll we’ll talk about that in at a later time but yeah you want to initialize your variables first I’m just going to get rid of that now when it comes to naming your variables there’s a couple conventions that we need to follow so variable names can only be letters numbers underscores and dollar signs okay so you can’t have anything else you can’t have like a plus symbol or an asterisk or anything like that and even though that you can have numbers they can’t start with a number so if I were to say like let one name equals Brad that’s not going to work I’m going to get an error but if I move that one to the end here then that’s fine but if I try to add like a plus sign or something like that that’s not gonna that’s not gonna work okay now as far as the formatting of your variables for like multiple words just paste this in here what I did here with first name and last name this is called camel case where you start with a lowercase number for the first word and then every other word after that is uppercase okay so that’s camel case and that’s usually what you’re going to see now you have other ways to do it like you could use underscores to separate The Words which I don’t particularly like but I mean it is it’s all right I guess you see a lot of that in PHP and then we also have Pascal case where the the first word is also uppercase and there are conventions or there are certain times where this is the convention such as in react components or most front-end Frameworks when you create a component the file name is Pascal case so is the class or the function name of the component and then you might see all lower case which I really don’t like I don’t think that it’s very readable especially if you’re getting into like three and four words okay so let’s look at reassigning variables so we’ll say reassigning variables now we have a variable up here of age you we use let we set age to 30. so if I come down here I can then take age and then I can reassign it to let’s say 31 let’s say John had a birthday and then we’ll just console log age again and now it’s 31. all right now another thing I can do with let is just simply declare it and not actually assign a value so let’s say we want a variable called score but that’s it I’m just going to declare it okay I’m allowed to do that I don’t get any error and then I could take score and maybe add 1 to it let’s do a console log of score and we get 1 and then we might have like some kind of if statement I’ll just put true in here so that this runs and and don’t worry if you don’t understand this but let’s say we had we have something happen where the score and gets added one again we’ll say it equals score plus one and then down here we’ll console log again score and now we get two okay so that’s something that is very common using let now let’s try the kind of the same thing with const so we’ll go ahead and say const and I’ll just I’ll just call this X and I’m going to set that to 100 and then let’s say I want to take that X variable and then reassign it to 200. if I save that I’m going to get an error it says assignment to constant variable a type error okay so a constant cannot be directly reassigned like this another thing you can’t do with const is just declare it and not initialize so for instance if I were to say I already have score so I’ll say score one if I were to just do this you’ll see it’s already giving me an error here const declarations must be initialized if I save I’m going to see the same same error here okay If This Were A let though that I can do that okay so just know that const can’t be directly reassigned now where a lot of people get confused is when you’re using arrays or objects things that are not primitive values and I know I haven’t gotten into that stuff yet but I just want to show you a quick example that’s pretty easy to understand so if I use const and I have an array right and and an array is just multiple values so let’s say one two three four all right what I can’t do is directly reassign by taking array and saying well let’s do one two three four five if I do that I’m going to get an error because I’m using the equal sign directly reassigning but what I could do is with a raise you have a bunch of methods such as push and pushes is a method that will add on to the end so what I could do is say array dot push five and then if I console log my array that works so I manipulated this array I changed it to from one two three four to one two three four five by simply using a method to push five onto the end okay and then the same goes with objects if I say cons person and I set that to an object and I say name Brad and then we’ll come down here now if I were to just take person and directly reassignment you guys know that’s not going to work but I could do person.name and set that equal to John and that works because I’m not I’m not directly changing the variable I’m changing a property or a key inside the variable or not a key but a value of a key okay I could also do like person dot email and I could add on let’s say Brad at gmail okay and then if I do a console log of the entire person object you’ll see I have name John and email Brad Okay so when people ask me you know what should I use cons let or both or whatever I say it’s it’s it’s really preference now for me I always use const unless I know I’m going to directly reassign something like like this right here okay um now you’re gonna find that you don’t do this very often okay I shouldn’t say that I don’t do this very often we use a lot of the times we use objects and arrays and using Cons with that is just fine because there’s not too many you know you don’t directly reassign this very often you’re going to do stuff like this you’re going to use methods you know you’re going to assign properties and stuff like that so that’s my rules I always use cost unless I know it’s something that I’m going to change such as a score and a game you know you might add to that but you probably or what I would do is have it in an object and then just change that value so I could use const in that case so I mean you’re going to find a lot of this stuff is preference all right now another thing that I just wanted to mention is we can declare multiple let’s say multiple values at once or multiple variables so I’ll just go ahead and say actually let’s use let here let’s say let and I’ll say ABC so I could do that right I don’t even have to assign it because I’m using let and then I could also do like const I can’t just I have to assign it but I still can do multiple at once so I could say like a I can’t do a because I just used it up there but let’s say d equals 10 I could put a comma and say E equals 20 and let’s say f equals 30. okay and all of that is just fine so if I console log d down here you’re going to see we get 10. now I usually don’t do this I’ll just use a semicolon and then just do const d const d const f I just think it looks cleaner but that’s just again that’s just preference but you can assign you know multiple at the same time and if you don’t actually assign a value and you log it what we’re going to get is undefined okay which is one of the data types which is what we’re going to talk about in the next video all right guys so I want to spend a little bit of time on data types so when you’re dealing with code any any type of code any language and you’re dealing with data that data is associated with some kind of data type okay and it doesn’t matter which language you’re using they all have some kind of data types and they can be different language by language now in JavaScript you essentially have two types of types you have primitive data types and you have reference types or objects and I’ll talk about those in a second but I want to start off with primitive data types now I feel like a lot of JavaScript courses kind of skip over some important fundamentals and what I want to do is I’ll talk more about this in the next video but I want you to understand how these data types are stored and how primitive data types are different or are accessed differently than reference types but again I’ll talk more about that in the next video right now I just want you to know what these types are so the first is a string which we’ve dealt with so a string is essentially a sequence of characters and a string must be enclosed in either double quotes or single quotes or back ticks next we have a number which are integers which could be positive or negative numbers as well as floating Point numbers or decimals now in some languages you actually have either a decimal and or a float type in JavaScript we don’t what if it’s a integer or if it’s a decimal or floating Point number it’s they’re all the same they’re all going to be then the type of number okay so keep that in mind next we have a Boolean which represents a logical entity it can be either true or false next we have null which is the intentional absence of any object value and a lot of people get null confused with undefined which I’ll talk about next but just know that null is it’s always it’s intentional it’s supposed to be there but it’s supposed to be null it’s supposed to be empty you can essentially think of it as empty now the next one undefined is a variable that hasn’t been defined or assigned okay so null is purposeful undefined usually isn’t all right next we have a symbol which I’m not going to talk too much about right now because it’s it’s kind of advanced and and it was actually added in es2015 or es6 so a symbol is essentially a built-in object whose Constructor returns a sim a unique symbol or a symbol that is unique all right and and we’ll get into that later it’s not something you use very often at least I don’t and then the last one is a new data type that was just recently added called Big int okay and it just represents really really big integers really large numbers that the number type can’t handle all right and we will jump into some code in this video and just kind of show you how to how to store each of these in a variable so the next type of type is reference or objects now reference are objects they’re non-primitive and when we assign a reference type to a variable the variable is given a reference to that value and again I’m going to talk more about how reference types and primitive types are stored and accessed in the next video but object literals arrays functions these are all examples of reference types now in programming you have something called Static typing or statically typed and you have dynamically typed JavaScript is a dynamically typed language and what this means is that we don’t explicitly Define the types for our variables so if I say like const name equals Brad I don’t have to put const name String equals Brad it just knows it’s Dynamic with many languages you actually have to you have to add the types yourself those are statically typed languages like C C plus plus Java and I’m sure that some of you have worked with some of those languages in JavaScript you don’t explicitly set your types however there is something called typescript which is very very popular and it’s a superset of JavaScript meaning that it’s everything that JavaScript is it essentially is Javascript but it also has some additional features including static typing okay so there are reason to use static typing it is more code that you have to type but it can make your code more verbose and it can make it less prone to errors and a lot of people really love typescript so that might be something you want to look into once you really learn the fundamentals of JavaScript okay so I just want to jump into vs code and go over these types in the text editor and also show you how we can get the types of a specific variable so let’s start off with strings which are very simple just they’re just sequences of of characters so I’ll create a variable and I’m using const like I said in the last video I use cons for everything unless I know I’m I’m going to reassign it so we’ll say first name and we’ll set that to Sarah alright now I want to console log out the value so we’ll say first name but I also want to show you how we can get the actual type from this first name variable so as a second argument I’m going to pass in the type of operator okay so just type of and then a space and then whatever you want to get the type of sole first name and now you’ll see it’s logging out Sarah and string all right now there’s going to be a few variables that I want to show the value and the type and I don’t want to type it twice so I’m going to create another variable here we’ll just call it output and for now I’ll set it to first name and then let’s come down here and and put output now I just want to mention some little little tips and tricks as we go along I already went over some shortcuts but just to kind of remind you we can go to the the end of this first name hold shift and then highlight it and then we can do a command or control D to select the next instance of first name and then replace it with output and then save okay and we should get the same result so I’ll just mention little tips and tricks like that as we go along so the next type I want to look at is number so let’s do const we’ll say age equals 30. so that’s an example of a number if I change that to age we get 30 and it shows number from our type of operator now I also want to mention that decimals so if I do temp and set that to let’s say 98.9 and then we look at the type for that that’s also going to be a number there’s no specific float or decimal or anything like that everything is a number in JavaScript so the next type is Boolean which is really simple it’s just a true false value so maybe we want to say like has kids since we’re talking about a person and we’ll set that to true and then we’ll come down here we’ll change the output to has kids and we get true when it says Boolean so the next one is no which is basically like an intentional empty value so maybe we have like an apartment number but let’s say this person lives in a house so we set that to null there’s no apartment number there’s no need for one and this one is a little weird because if we set this to apartment number and we look at the value which is null and then we look at the the result of this type of we get object okay now this is a little confusing because null is not an object it’s not a reference type It’s A Primitive but there’s a reason for this it’s kind of in summary it’s kind of a mistake in fact I’m going to paste in the um the link right here if you’re interested and we can check it out real quick so let’s go to that link and it just kind of explains why this happens uh and it has to do with the first implementation of JavaScript values were represented as a type tag and value the type tag for object was Zero null is represented as the null pointer which was 0 x 0 0 consequently null had zero as a type tag hence the type of Return of object so in case you’re wondering why it says object and not null that’s why but it’s not it’s not that important honestly now the next is undefined and you’re probably not going to purposely set variables to undefined very much but just to show you if we were to do remember in the last video I showed you we can we can use let to just create a variable but not actually Define it to something so I’ll just say let’s score and then we’ll pass that in here to Output so we can see the value in the type and both are undefined the value and the type okay so if you just set a variable and you don’t Define it it’s going to be undefined now you can also explicitly set it to undefined you don’t do this very much but I could say cons score let’s just comment this out and I could just say set it to undefined and we get the same thing all right now a symbol is A Primitive type but it’s not something that you’re probably going to use very much especially in in you know your early career but just to show you we can create let’s say ID and let’s set that to a symbol so we’re going to say symbol with parentheses and then pass in a unique identifier of ID and then we’ll change this to ID and save and you’ll see we get symbol as our type and then the last one is although I should say the last primitive type is Big int which is just a really big number that is too big for the number type so I’ll say const n and I’m actually going to just copy or paste in this number here so it’s basically this long string of numbers and then n and if we were to put n right here and save we get the type of big end now as far as reference types let’s come down here and in the next video I’m going to talk about the difference in how these how primitive and reference types are stored and accessed but as far as what reference types are are arrays object literals functions so just to give you an example we’ll create a simple array I’ll call it numbers okay and then if I were to actually we want to put let’s grab this and let’s put this up here we want this above the output and then let’s change this to numbers okay if I save that it’s going to show the array as the value and object as the type okay any reference type is an object so an object literal of course is also an object is also a reference type so if I say person and we’re going to learn all about objects and arrays and get much more advanced but just to show you we’ll say Brad and then if we change this here to person you’ll see we also get object Now function is also a reference type so I’m just going to create a very simple function called say hello and just have it do a console log of hello and then down here let’s swap this out for say hello so you’ll see for the the value for the console log of the value it’s just the function itself I didn’t call it with parentheses and notice that instead of object it says function now it’s still an object it’s just defined as a function object and I’m going to put the documentation link here if you want to read more about that and in the final version of the sandbox I’ll label what these links are and stuff so I’ll make things a little neater but yeah that’s it as far as what the the types are the Primitive types and reference types or objects in the next video I just want to quickly go over how those are stored in memory all right guys so in this video we’re going to look at how primitive and reference type data is stored in memory and one thing I want to mention is if you’re a beginner and some of this is kind of confusing that’s okay that this is kind of like behind the scenes stuff and the reason I’m I’m putting it in the course at this point is just to give you a a bigger picture of not only the syntax to write for you know your JavaScript code but to also understand how JavaScript works so if you don’t completely soak in this video that’s that’s absolutely fine you can always come back to it later and we’ll talk more about this stuff later as well so when we store our data when we set a variable if it’s a primitive type it’s stored in an area in memory called the stack okay if we store reference type such as an array an object a function that’s stored in an area of memory called the Heap okay so you have the stack which is where your primitive data is stored and you have the Heap where your reference types are stored so just keep that in mind all right now to to kind of visualize how we store and access data I created this this diagram with kind of multiple scenes so first off let’s say we create a couple variables we have a name that’s equal to John which is a string which is a primitive type and then age equals 30 which is a number which is also a primitive type now this box over here represents the stack in memory so you can see age the name of the variable and 30 the value are stored on the stack same thing with name and John now if we were to create a variable called person and set that to an object which is a reference type you can see the variable is stored on the stack but it acts as accesses the data by reference and that data is stored in the Heap all right now just to kind of show you more about how this works if we create another variable called new name and we set it to name okay up here which is John then on the stack we have a new variable called new name and we have a new piece of data called John name is still equal to John and now new name is equal to John let’s say that we want to take that new name variable and reassign it remember when we use let we can reassign so now we have new name equals Jonathan so it overwrote the old value of John to Jonathan now let’s kind of do the same thing and say well we’re going to create a new person variable and set it to person which is this object right here Brad name Brad age 40 41 now but that’s fine so new person is put on the stack the variable and it points to the same reference that person does okay so it doesn’t create a whole new value like up here where we created John again it just points to that area in in the memory Heap so if we were to let’s come down here and let’s say new person dot name which is a property this property right here set that to Bradley now what’s going to happen is we’re changing in the Heap that name value of Brad to Bradley so new person.name is going to be Bradley but so is person.name in fact right here if we logged person.name it’s going to be Bradley even though we changed new person.name the reason for that is because they both point to the same reference all right so that’s kind of what I want to get across here is with primitive types the value is stored on the stack so even if you change new name to something name is going to stage on because John is there it’s solid on the stack with objects and arrays and so on you just you have a reference so if you set a variable to another variable and change something in that it changes the the reference so what I want to do now is jump into vs code and show you this this exact thing in the text editor so I have this empty script JS and we’re going to do the same thing let’s say const name equals we’ll set that to John and then we’re going to set the age equal to 30. so these are both primitive values in fact I’ll put a comment here let’s say these values are stored on the stack all right now let’s say reference values are stored on the Heap so let’s say const and we’ll say person equals and let’s set that to let’s say name and we’re going to have an entire section on object literals like this so don’t worry if you don’t fully understand the syntax so we’ll say age 40. all right so we have our permanent values and we have our reference values so I’m going to do what we did in the uh in the slide and let’s say new name and I’m using let here because I’m going to reassign it so say new name you set that to name and let’s just do a console log down here of both name and new name so now we get John and John for both the name and new name and don’t worry about this being crossed out it’s just because name is a deprecated property on the window object it has nothing to do with what we’re doing so now let’s go ahead and reassign we’ll say new name and we’ll set that now to Jonathan so if I save that now we get John and Jonathan now let’s try the same thing with the reference type so I’ll say let new person set that to person and then down here let’s console log person and new person and we get both they’re both the same right name Brad age 40. so now what I’m going to do is take new person which I got the value from uh from person but remember these are stored in the Heap and they’re accessed by reference so if I were to change the new person name to Bradley and I save that notice both person and new person both are now Bradley okay because these are both stored in the same spot in um in the Heap and they’re being accessed by reference and that diagram should really help you understand why it’s doing this right you can see they’re both pointing to the same spot but with the Primitive values the values are stored right on the stack all right so I hope that this made sense in the next video we’re going to look at type conversion because sometimes your types can change whether it’s implicitly or explicitly so we’re going to talk about that next all right guys in this video we’re going to talk about type conversion so type conversion or type casting is the process of explicitly converting a value from one type to another for instance you may have a string value of five so five with quotes around it and you want to convert it to a number of five so that you can maybe do some arithmetic operations on it or whatever you’re going to do now there’s also something called type coercion which can be explicit but it usually refers to having your types changed implicitly okay without you you know purposefully doing it so we’re going to talk about that in I think the video after the next one but in this one I’m going to show you how to explicitly convert types now let’s say we want to convert a string to a number so I’m going to say let amount and I’m using let because I’m going to reassign this but let’s set it to 100 wrapped in quotes and then let’s do a console log of the amount value as well as the type so we’ll say type of amount and if I save that you see we get 100 and string so there’s there’s a few reasons you might want to convert this to a number if let’s say someone’s submitting a form and the number comes in as a string but you want to run some operations on it you can’t do that with a string you want to change it to a number so there’s a couple ways we can do that the first is using the parse int function so we can say amount I’m just going to reassign it to let’s say parse int which is a function so we use our parentheses and this is going to take in the string okay which is in the variable of amount so now if I save that you can see we get 100 which is now a different color and we get number as the type now another way to do it is by using the the unary I think it’s called unary operator it’s just basically the plus sign and this is the method that I like to use it’s a newer way to do it so we can say amount equals and then just do plus amount so if I save that you can see that also converts it to a number and then the third way we can do it is with the number method or the number Constructor and we do that by just saying number with parentheses and then we can pass in a string and I save that you can see now we get it as a number so those are some different ways you can use to parse it to a string to a number and I’m just going to put a comment here let’s say change string to number all right now let’s look at some ways that we can change a number to a string so I’m going to come up here and change this to 100 which is a number if I save this you’ll see it’s a number and now I want to change this to a string so one way we could do it is say let’s say amount equals amount and then there’s actually a method called to string okay so a method is a function that’s attached to an object now if I save this you’ll see it’s now a string now this this actually brings up a question or it should bring up a question we know that this this right here is a number which is a primitive type which means it’s not an object now methods are properties on objects so so why does this work you know this should be a primitive it doesn’t have methods well the answer to that is Javascript actually creates a temporary wrapper if when we use two string it creates a temporary wrapper of the appropriate object type so this amount which is a primitive doesn’t intrinsically have any methods on it because it’s not an object but since we’re trying to use two string on it JavaScript creates a temporary uh wrapper of the associated type okay so hopefully that makes sense now that kind of stuff isn’t really beginner JavaScript but like I said I want to touch on some of the the fundamental concepts and how JavaScript works as you go through this course so you might not retain little things like that but that’s okay you know if as long as you remember the syntax and you know what’s going on that’s fine you don’t really have to know what happens under the hood but I will I do want to just talk about some of that stuff now another way we can do it is we can say amount equals let’s just comment that out so we’re going to say amount equals and then we can also use the string Constructor just like we have a number Constructor so I’ll pass in here Mount and now if I save that you can see that it is a string now if you have a decimal right so if let’s say this is amount is 99.5 and you want to let’s say it’s a string of 99.5 and you want to convert it to a number of 99.5 which is a decimal there’s a method you can use called parse float you don’t want to use parse int because that’s going to be an integer which is either a positive or negative number so let’s come down here and let’s say change string to decimal so what we can do is say amount equals and to use or to change it to a decimal we can say parse float and pass in the amount and then let’s save that now the actual type like within JavaScript is going to be number but let me show you what happens if we use parse int if I say Parts int and I save it’s going to be an inch it’s going to be 99. the the type underneath is still number either way but it’s going to screw up your formatting if you need this to actually be 99.5 so in that case you definitely want to use pass float all right I’m just going to change this to change change to convert okay so the next thing I want to show you is the Boolean Constructor which will turn a number into a Boolean now in JavaScript we have a concept of truthy and falsy values and I’m going to get into that soon but for now just know we can actually change a number so let’s make let’s make this back into 100 actually let’s make it into a one and then let’s come down here let’s say convert number two Boolean and I’m going to say amount and I’m going to set that to Boolean remember Boolean is a true or false value I’m going to set that to amount let’s see what we get so as you can see we get true and we get the type of Boolean now one is what we call a truthy value if we convert it to Boolean it’s going to be true if I set this amount to zero and we save we’re going to get false okay zero is a falsy value and I know that that sounds confusing but I’m going to have a whole video on truthy and falsy and then any other number like 10 or anything else is going to be true 0 is the only one that’s going to be false now let’s look at what happens if I’m just going to comment this out let’s look at what happens if we try to take a string that is not a number and or I should say is not a number in a string like something like hello and what if I try to parse that into a number let’s see what we get so we get a value of Nan or Nan and what this stands for is not a number okay it’s uh it’s actually a special number as you can see it does have the type of number but it’s a special number that represents not a number and it can this is kind of confusing um so there’s some really strange and quirky aspects of JavaScript the good news is most of it doesn’t get in your way in Practical development it’s just when we start to Dig Down Deeper if things can get a little weird so Nan is a property of the global window object and it’s a non-writable property and there’s actually five different types of operations that can return Nan and that’s when a number can’t be parched which is what we’re seeing here also math operations where the result is not a real number like trying to do like square root of negative one in fact I’ll just say console log and I know we haven’t talked about the math object yet but there’s a square root here and I’m going to do negative one if I save you’ll see that also gets Nan another one is if the operand of an argument is Nan like if I do one plus Nan let’s try that console log one plus n a n okay we get Nan also if we try to do like undefined let’s say undefined Plus undefined that gives us Nan and then the last way we can get it is any operation that involves a string and is not an addition operation so if I do like a string let’s say Foo and we’ll say divided by three I also get Nan so those are the five ways that you can end up with this but the most common thing you’re going to do here is convert a string to a number especially when you’re dealing with like form data because you might want to do some operations on a number that you can’t do on a string all right so that’s it in the next video we’re going to look at operators all right so in this video we’re going to take a look at operators so operators are symbols that we can use in Expressions to do certain things and there’s a few different categories of operators the first first one I want to look at is arithmetic so let’s say one and let’s say arithmetic operators all right so these are going to be pretty simple obviously you guys know addition and subtraction and all that but I’m just going to initialize a variable just to Output so I’ll say let X and then down here we’ll say just console log X and let’s say x equals and we’ll just do five and say five plus five so this is obviously the arithmetic the addition operator if I save that of course we get 10 copy that down let’s do minus we get zero let’s do we’ll copy that down again and we’ll do multiplication that gives us 25 and then we’ll do division that gives us one now in addition to those the you know the basic four we also have the modulus operator so if I say well if I do five and then the modulus which is the percent sign and 5 that’s going to give me zero because 5 goes into five once with no remainder so what this does is it gives us the remainder if I were to do 7 we know 5 goes into 7 once if I save that you’ll see we get 2 as the remainder so this this can come in handy for different things now the next thing I want to show you is concatenation I think you spell it concatenation so the concatenate concatenate operator is the plus sign so you can essentially think of the plus sign having two different functions in JavaScript one obviously is addition but one is to concatenate strings together so if I use the plus sign with two strings well let’s say X equals so I’ll say hello which is a string and then plus and then another string of world if I save that what it does is it just concatenates or puts the two together all right now if I wanted a space in between I could either put a space here that works or you might do another you might concatenate again just a set of quotes with a space but if I want to go back to another string then I would add another plus sign here so that’s concatenation I came to JavaScript from PHP like I learned PHP first and in PHP the period is the concatenate and concatenate operator so this does the same thing that the period does in PHP so the next one is the exponent operator which is a double asterisk so let’s say x equals and what we’re saying here is we want to get the result of the first operand to the power of the second so we’ll say two double asterisks 3 and that gives us 8. all right so that’s exponent then we have increment so increments there’s a couple ways that we can increment a number so let’s say we have X let’s set it to three actually we’ll set it to one and then let’s say I want to increment it by one I could do x equals X plus one if I do that we get 2 or I could use the increment operator which is double double plus sign if I save that I also get 2. and of course we can also do decrement so right now X is two so let’s say x equals x minus one so that’s one way that we could subtract one or we can just do x minus minus and that also gives us one so those are all the basic arithmetic operators now we’re going to look at assignment operators so the first is just a value assignment which is very simple we’ve been doing that all along so we can just say x equals 10 that’s just assigning a value now we also have addition multiplication subtraction basically all the stuff we did up here we can use those as assignment operators so what I mean is I can say x and then plus equals let’s say five and if I save that we get 15 because X was 10 but then this is the same as it’s the same as doing this x equals whatever X is Plus 5. and in fact if we did one that’s the same thing we did up here to increment right same thing as this as well and then we can also use other we can say like minus equals that gives us 10 because remember it was 15 but then we took 5 away then if we do the multiplication so we get 50 then we can do division we get 10 and we can also do modulus which gives us zero there’s even the exponent I’ve never used this but you can also do that so those are assignment operators now the next batch that I’m going to show you let’s say three these are comparison operators which you’re going to use quite a bit so the first one is is if something is equal to and I’ll comment these a little better for the final version but I don’t want to waste too much time with comments so let’s say x uh we’ll say x equals and then let’s say 2 and I’m going to use the equals operator which is double equals okay remember the single equal sign is assignment that’s what I’m doing right here I’m setting something to X but right here I’m evaluating an expression using the comparison operator of equals so what that’s going to give me is true it’s going to give me the result of this it’s going to put that into the variable and then I’m you know console logging that now if I were to change this to 4 then obviously that’s going to give me false so that’s equal to now we also have the equal value and equal type operator which is a triple equals so let’s say 2 and then let’s do triple equals two now that’s going to give me true obviously but I just want to show you if I were to comment this out for a second and then on the double equal change this to a string that’s going to give me true because the double equal does not test the type it only tests the actual value inside all right now if I were to uncomment this and make this to a string and save I’m going to get false because the triple equal not only evaluates the value but it evaluates the type as well so the types have to match and in this case this is a string this is a number now it’s really preference on what you use but what I do and what I’ve what I see a lot of people do is pretty much always use the triple equals I think that that’s going to save you some headaches and save you some hours if you just always use triple equals there are a couple situations where you might not want to there’s there’s quite a few where you don’t need to but it’s in the most in most cases it’s not going to hurt all right so that’s just what I do it’s up to you you’ll you’ll kind of find your groove as you as you move along all right so let me just put a space here now we also have not equals so I’m going to say x equals 2 and the knot is is represented with an exclamation so I’m going to say not equal but just one equal in this case so this is this is basically the opposite of this even though it only has one equal sign so I’m going to say 2 and save that and we get false and the reason we get false is because 2 is equal to 2. so obviously 2 not equal to 2 that expression is going to be false now same rule applies with the double equals as with this if we were to do a string that’s still going to be false because in this case 2 is equal to this if we’re using the double equals now we also have the not version of this so if I were to copy that down and then let’s just add another equals onto that if I save that we’re going to get true and that’s because it’s true that this is not equal to this when we’re checking the type as well if I remove these quotes and save that that’s going to be false because it’s false that this is not equal to 2 because they are equal all right now the next thing I want to show you is greater than less than which are pretty simple so let’s say x equals 10 let’s say greater than 5 and then of course that gives us true and we’ll just copy this down and let’s change this one to less than so that’s going to be false we also have greater than or equal to and we have less than let’s do yeah I’m sorry that’s less than or equal to then we also have greater than or equal to so very simple those don’t really need any explanation if you did like third grade math so that’s all I want to talk about in this video basically I needed to you guys to know this stuff in order to understand the next video of type coercion so a couple videos ago we looked at type conversion where you as a developer you want to change a string to a number or a number to a string in this video we’re going to look at type coercion which is more implicit and typically coercion happens when you apply operators to values that have different types so what I’m going to do is just create a variable of X and I want to console log the value of x and also the type and the reason I do this is just so we don’t have to create a bunch of different variables so let’s say we want X to equal the number five plus the string with 5 in it and let’s see what we get so if we look in the console you’ll see we get 55 but we get it as a string so this is an example of type coercion where JavaScript implicitly changed this to a string all right because what happened here is it was concatenated with the plus sign so if I were getting a string for some reason and I wanted to add it then I would convert this first so for example actually let’s just copy it down because I’d like you guys to have all the code we write and let’s just wrap this in a number and then that will obviously add them together because now this is a number now what if we were to say x equals five and then let’s multiply a string what do you think we’re going to get here so if I save that we get 25 which is a number so JavaScript in this case did the opposite it converted or coerced this string into a number and the reason for that is because if you use multiplication between strings that doesn’t make any sense you’re not going to get anything from that so JavaScript decided to coerce it to a number so it could be multiplied so let’s see what happens if we do x equals and let’s say 5 plus null in that case we just get 5 as a number so no is actually coerced into a zero and we can see that if we do let’s say x equals and we’ll use the number method here and pass null in and you’ll see we get 0. okay and you can use this on anything this number so if I say number let’s do copy that down we’ll do true and false I’m just going to comment out this one to see what we get for true you can see we get one so true as a number is one false as a number is zero so with that said what do you think happens if we say let’s add five plus true let’s go ahead and save that we get 6 because true is being coerced into a number and true as a number is one okay same if we do let’s say five plus false obviously we’re going to get 5 because false is zero as a number and again we’re going to talk about truthy and falsy values in a little bit so if we do let’s say x equals 5 plus undefined we get Nan which is not as a number now remember in the what was it was it the last I think it was the last video where we talked about Nan and if we add anything to undefined um then we’re going to get Nan okay including itself so now you should be pretty familiar with types we have our seven primitive types and then we also have reference types or objects and we talked about how they’re stored in memory we talked about implicit and explicit type conversion or coercion so what I want to do now is focus on individual types such as strings and numbers and start to look at how we can use them manipulate them use some of the methods that we can use with strings and numbers and just get you a little more familiar with that all right so we’ll look at strings next all right guys so we’ve looked at the different data types the Primitive types versus the reference types or objects we’ve looked at conversion and coercion and operators what I want to look at now is individual data types and just certain things we can do so in this video I want to look at strings so we’ll talk about concatenation a little bit more as well as template literals which are really really helpful and also some of the different methods that we can use on a string now like I said in a past video strings are primitive however they if we use a method like let’s say two uppercase on a string which is primitive JavaScript puts a wrapper around it and makes it a string object so in that case we can use methods all right so let’s start off here by initializing a variable I’m just going to say let X because I’m going to do a lot of output so let’s say console log X and then we’ll start off here with concatenation which we’ve already gone over we basically have our string actually you know what I’ll do is uh let’s let’s do like a sentence we’ll say hello my name is and then I want to put a variable and I’ll set those variables here let’s say name equals John or whatever you’d like and then let’s say const age equals 30. now here I want to use the name variable so what I would do is concatenate name and you don’t want to put quotes around this because it’s a variable and then we want to concatenate back into a string and never mind this strikethrough it’s just because the window object has a deprecated property of name but it doesn’t concern us and then I want to say and so my name is John and I am space concatenate on the age plus and then let’s do another space here in the quotes and years old so that is you know kind of kind of a pain in the ass but if I say we say hello my name is John and I’m 30 years old if we change this to let’s say 31 and save obviously that’s going to Output now I want to show you how to do this same thing using something called template literals also called template strings so I’m going to take X and just overwrite what we just did and I’m going to use back text this time okay so back ticks are used for template literals not quotes and then we can do the same thing we’ll say hello my name is now instead of having to you know put a space here and then concatenate here what we’ll do is use this syntax a money sign and then curly braces and then in here I can put my variable if I save that you’ll see it says hello my name is John now this isn’t just for variables the syntax it’s for any JavaScript expression in fact I could just do like one plus one and it’ll evaluate it to two so we can essentially write our JavaScript in here so I just wanted to say name and then I’m going to just space and then and I am I want to put my age here so again I’m going to use the syntax and say 30 31 years old and you can see that that output’s fine so this to me at least is much much easier and cleaner than this so you’ll be using template literals quite a bit now template literals didn’t come into JavaScript until 2015. it was the es2015 or es6 update was where template literals were were introduced before that you would have to do this so now what I want to do is look at properties and methods or let’s say string string properties and methods so if I say let’s say x equals and then hello world actually I’m going to give this a different variable let’s say const s equals hello world so we have a string of hello world and if I want to let’s say get the length there’s a length property for that we can use for Strings so I’m going to say x equals and then s which is our string and then dot length now since it’s a property we don’t add the parentheses methods use the parentheses because methods are functions properties are more like attributes so if I save that you’ll see we get 11. now as I S as I said earlier the strings are primitive but we can use properties and methods on them because of the wrapper that JavaScript gives it when we run these properties and methods so essentially what JavaScript does behind the scenes Let me just show you real quick if we were to do let’s say x equals type of and then we’ll do type of s and let’s just comment that out because that’ll overwrite it so we get string right but what the wrapper does when we run a property or method is it basically says new string and it creates this string object now if I save you’ll see I get object okay and I’ll just leave it like that you can leave it with just quotes hello world or you can use this new string but I’m just trying to let you know what happens kind of behind the scenes when we use a method or a property and we can also access the the the individual characters so for instance if I say let’s go down here if I say x equals and then S I can use this syntax and it starts at zero just like an array if I save that you’ll see I get H I get the first character if I do one I get e so I get the second character and so on okay and I’ll just put a comment here we’ll say access access value by key so we have number key numbered keys now another thing I want to show you and we’ll get much more into this later with object oriented programming is objects have what’s called a prototype and that’s where the methods are stored so if I do x equals and the way we access the Prototype is double underscore Proto double underscore and I’m setting that to X so I’m going to save and show you what we get here so if we look down here we have all these different methods so for instance we have two uppercase two lowercase we have split substring all these different methods that we can use with strings and I’m going to show you some of them not all of them I’ll show you some of them now some of them later and and some you’ll never use which I probably won’t won’t get to but you can see all these different methods that are available on the Prototype so and if we console log s and I save that if we look down here you’ll see prototype right here which has the same thing so this is is the same thing as this all right and it even shows you the different Keys the different numbered keys but let’s put that back to X and now we’re going to look at some of these these properties so if we want to change the case we could do x equals let’s say our string and then we’ll do two uppercase which is a method so of course we need our parentheses if I save that we get hello world and all uppercase I’m actually going to comment that down and we also have two lowercase okay so that will change the case there isn’t a method that will make like the first letter of each word uppercase but we can do that in JavaScript it just there’s no single method to do it I’ll show you that in a little bit so the next one is Char at and that will return the character at the specified index so if I say x equals s dot Char at and let’s say we want to get the first character that would be zero if I save that that gives us H which is essentially the same as as what we did up here where we were accessing by the key so this will give us the same as this now if we want to know the index of a specific character so kind of the the inverse of this we could say s equal x equals s and we can use index of so if we say index of and let’s say we want the index of H if I save that we get zero let’s say e now there’s more than one e what this will do is give us the first e which is the the number one index which is the second character so this right here because it’s 0 1 2 3 and so on if we put let’s say d that will give us 10 which is the the last index so the next one is substring which will search a string for a specified value so let me show you if we do s dot and then substring and then we can this will take in two indexes so let’s say we want to get from 0 to 4. if I save that we get hell because if we look at hello world and by the way this could be just a string you know just the quotes hello world if I change this s to that and save we get the same thing but I just did that to show you basically how to how to turn a string into a string object so we get hell because it’s 0 1 2 3 and then it ends at four all right if we want to get hello then it would be zero to five save that we get hello and we don’t have to start from zero if I do one and save we get lo you know Edo Governor if we do 2 to 5 we get llo all right so you can get any it’s it’s a substring it’s just basically a string inside of a string and another thing we could do is run substring with a single argument let’s say seven if I save that we get o r l d so what this did is it started at seven and then it just gets the rest of the string all right so zero one two three four five six seven so it started here o is seven and then just went to the end if I put a bunch of stuff on the end of this and save it’s gonna add that to it now the next one I want to show you is slice which is very similar to substring in fact I’m going to just copy this and we know that 0 to 4 will give us access to zero to five that’ll be hello and actually I’ll just save it you’ll see it get hello with substring and if we do slice we also get hello now there’s a few differences one of them is that with slice we can start from the end with negative numbers so for instance if I do let’s start we know that hello world altogether is 10 right it’s 10 characters or 0 through 10 I should say and if we want to start the beginning using negative we could do negative 11. so if I do that and then actually if I just do that we’ll get hello world because it starts at the beginning negative 11 all the way to the N now if I want to get the word hello we could do let’s see that would be negative 10 nine eight seven I think negative 6 should give us so if we save that yeah so that now we get hello so we’re basically just starting from the end yeah so I mean you could use substring or slice interchangeably in a lot of different situations another one that I want to show you is trim so let’s uh let’s say s dot trim and what this does is it trims the white space so what I’m going to do is set let’s just do this we’ll say hello world but I’m going to add you know a bunch of white space here and if I were to just do that you’ll see it it adds the white space here to the beginning but if I were to use trim and say x equals x dot trim and save it gets rid of that white space so that can be pretty helpful next let’s look at replace so I’m going to say x equals and let’s set um so we’ll take string and then we want to replace and let’s say we want to set the word world to I don’t know John so what we could do is search for a string within a string that’s going to be the first argument so we’re going to search for world and then the second is what we want to replace it with so let’s say John if I save that we console log X now we get hello John now let’s look at includes which will return true or false if a string is found within that string so if I say s dot includes and we want to let’s say we want to find hello if I save that we’re going to get true because this is found within that s string if I do hell that’s going to be true if I do Hal e or how I I save that that’s going to be false because this string is not found it’s not included in the hello world string okay so that’ll return true or false and then if we want to return the Primitive value of a variable so let’s say x equals s dot we can use value of and if I save that we’re just going to get the hello world okay even if we were to do this up here so this is a string object right if we console log s we get the string which is an object if we did type of acid should show object but if we want to get the true primitive of that which is a string we would use value of and then the last one I want to show you is split which you I use I’ve used quite a bit it’ll split a string into an array and it takes in a separator as an argument so let’s say s dot split and then if I just do that on its own it’ll just give me an array with the entire string inside of it now let’s say we want to split by the space because it’s hello space world then we would pass in here a space and now you’ll see I have an array with two strings and I know we haven’t really gone over a raise yet but we get an array with two strings okay if I wanted to split every character into an array item then I would just put just quotes if I do that now we have an array with 11 of items and each one is each character okay so that’s split now there’s a lot more methods so you can see here and I’m going to go over some of these in future videos some of them I won’t because they’re not really used that much but of course you can experiment on your own as well so I hope that this helped you understand some of the things we can do with strings now in the next video I’m actually going to give you guys a challenge based on the stuff we’ve already learned all right guys so we’ve arrived at our first challenge every once in a while I’m gonna ask you to figure out a problem or do something using the stuff that we’ve already learned okay I’m not going to ask you in any challenge to do something that involves something we haven’t done yet or haven’t learned yet now if you feel stuck or you can’t figure it out on your own that’s absolutely fine I’m gonna walk you through the solutions so that you can really understand how to solve the problem now this one is the capitalize challenge so basically what I want you to be able to do is take a string with a single word and just make the first letter uppercased we know we can do like so I could do my string dot two lowercase which would make it all lowercase or my string dot two upper two uppercase would make it all uppercase I want you to just uppercase the first letter now it doesn’t have to be a string with multiple words where you uppercase the first letter because in order to do that you have to to understand some type of iteration and I haven’t gone over any Loops or anything like that so I’m not going to ask you to do that if you already know that stuff and you want to do that that’s absolutely fine but yeah I just want you to basically take this my string which has a string of developer or it could be any word and when you console log my new string which should be a variable you create that has the uppercase D for developer or whatever the word is now just to give you some hints because this is all stuff we went over you can use the Char at method which will give you a character at a specific index you could also do this format where you have you know my string and then brackets and 0 1 2 3 Etc so you know how to access the first letter and then you also know how to make all of these everything uppercase and then you also know how to basically pluck out stuff from the string okay take strings from a string using either the substring or slice methods okay so using this stuff here you should be able to uh you know come up with this my new string which will have an uppercase for the first letter all right so go ahead and pause the video now and try and do that on your own so now what I’m going to do is close that up and we’re going to go ahead and solve this Challenge and I’m just I just want to open up my console over here as well so we know that we have a variable called my string and that’s set to a word a single word that’s all lower case we’re going to use developer and then I’m going to have multiple Solutions but they’re all going to be very very similar so I’m going to initialize my new string and let’s say this is going to be Solution One so we want to take my new string and then I want to set that to my solution now let’s remember the hints Char at is used to get the character at a certain index you can also use the bracket syntax and we know we want to get the first first thing here right first character so let’s say my string and then let’s use Char at and let’s say zero okay and then let’s just do a console log down here of my new string and the goal of this is to get my new string to be the word developer with with an uppercase D so we know that we can get the first character like this now let’s take that first character and make that uppercase so we can do that by chaining on to uppercase right so if I do that and I save now we have an uppercase d so what we need to do now is basically just take the rest of the string not including D and concatenate it onto it so let’s go ahead and I’m just going to close that up let’s concatenate and then I’m going to take my string which is developer with a lowercase D and I’m going to use substring okay so I’m going to say substring and I want to get just developer okay no D so what I can do is just put a 1 in here because what that’ll do is take the one position which which is e remember it starts with zero and it’ll get that over all right so now if I save this I’m going to get developer with an uppercase d now the other Solutions we can use are going to be very similar so let me just copy that down we’ll say solution two and then the only change I’m going to make here is instead of using Char at we can just use the bracket syntax so we can say my string and then we want to get 0. we’re going to uppercase that so that that makes the D uppercase and then again we’re just going to tack on or concatenate the substring which is the the rest of it the available if I save that we get the same thing so let’s grab these and copy these down and then this is going to be solution three and in this case what I want to do is instead of concatenating I want to use template literals so I’m going to get rid of the plus and basically what we have here are two different Expressions right the first one gives us uppercase D the next one gives us developer so I’m going to take the first expression and let’s put our back tick here and we’re going to wrap this first expression in curly braces okay and then the second one here we’re going to wrap that as well so that ends here and then we want to make sure we put the ending back tick on and we don’t need to put a space here so if I save that we get developer if I were to put a space here we’ll get this uppercase D and then available and another thing we could do is instead of using substring we could use slice okay so it just shows you that there’s multiple solutions for everything really and there’s a lot more solutions you could have including stuff that we haven’t gone into yet but as I said when I have a challenge for you guys it’s going to only include stuff that we’ve already gone over now if you wanted to uppercase every the first letter of every word you would have to iterate through it somehow and we haven’t gone over like for Loops or four each or any of that um so you know we have gone over turning a string into an array so you can take that as a clue as a hint if you do want to try it on your own but but that’s it for this challenge let’s go into the next video okay so just like we have string or methods and properties that we can use for Strings and we have string objects we have the same for numbers so let’s go ahead and create a variable here and I’ll set it to let’s say the number five and then I’m going to console log down here if I log number we get five if we look at the type of this variable it’s a number now we can also have number objects using the number Constructor so we can say new number and it probably won’t be too many times where you use this explicitly but like I said before it does JavaScript does put a wrapper around it and turn it to an object if you use methods but if we look at the type you’ll see now we get object and you can set this to five if you want or keep it like this I’m just going to keep it like this and then I’m going to just create a variable for our output because I just want to show you some of the methods that we can use now we’ve looked at two string so if we say num dot to string that’s going to give us the number as a string now there is no length property for numbers so if I were to say x equals num dot length you see I’m going to get undefined however if you want to get the length of a number like you want to know how many digits it is you could do two string right so just turn it to a string and then chain on length and now you’ll see I get one if I were to add let’s say let’s say 500 then it gives me 3. all right so that’s two string we also have two fixed which is going to give you or allow you to specify the number of decimal points so let’s say dot two fixed you can see we have the drop down of methods here so two fixed and I’ll say two and even though our number is 5 it’s just going to give us 5.00 now if we look at the type so if we look at the type of X you can see it is a string so if we take a number and then we use two fixed on it it’s going to turn it into a string representation of a decimal so let’s get rid of that and then if I were to let’s say this number I’ll make it 5.4567 if I save that I’m just going to get 5.46 now it gives me 6 because it rounded this up right if I were to do 4.52 and save that then I get 4.5 now we also have two Precision which is kind of similar but we count we we count the whole number so if we say three actually let’s do two and I save it then it doesn’t give me two decimal places it gives me two in total so we’ll do 5.5 and if I were to change this let’s say 4 5 to 4 2 and save that it’s going to give me 5.4 right if I say two Precision three then it’s going to give me three digits 5.42 so that’s two Precision we also have two exponential so say x equals nine dot nine num dot two exponential and that will get us the exponential of let’s say say two if I save that then we’re going to get that as a result let’s actually change this back to five so two precision and two exponential are ones that I don’t really use very much now you you might be working in a different location a different Locale so there is also two Locale string so if we do that and then I mean by default I think it’s going to do where you are so for me it would be en us since I’m in the US which just gives me five but let’s say you’re in Egypt which is I think AR Dash e g and save that’s the representation of the number five I guess I mean I don’t I don’t know the Egyptian numbers or whatever but I’m guessing that’s what it is all right so that’s two Locale string I’m just going to put that back to en dash us now there’s not too much else to look at as far as methods if we do num and we look at the Prototype I mean that’s pretty much it all the ones we looked at right I mean there is value of as well so if I do x equals num dot value of and we save that let’s console log X that just gives me the value right now there are on the number object itself there are properties so for instance we can get the largest possible number for the number type by doing number with a capital N Dot and then all capital Max underscore value so I’m going to set that to X so that’s the largest number possible that we can use with number and then if you want to get the lowest possible we can do x equals let’s say number Dot and then min value which is that number there okay so there’s not much else to look at in terms of methods that we can use on numbers so in the next video I want to look at the math object all right guys so JavaScript has a built-in object called math and this object has a bunch of methods on it that have to do with mathematical operations and it comes in handy when you need to do things like find the square root of something or round up or round down there’s also a helpful random method that you’ll probably use quite a bit so we’ll go ahead and take a look at that I’m just going to console log the math object itself and you’ll see that we have an object here that has some properties so it has pi for example and then a bunch of methods and I’m definitely not going to go over all of these and so some of them I don’t even know what they are or what they do and I’ve never used them but we’ll go over some of the common ones so let’s do let’s just create a variable to work with for our output so we’ll console log X and let’s say x equals let’s say we want to get the the um the square root of a number so we’ll do math Dot and then sqrt okay so that will get the square root of a number we’ll just pass in 9 here and if I save that we log out X you can see we get 3. so that’s the square root if we want to get the absolute number then we could use the ABS function so our method so we’ll say absolute and if I do 5 obviously that’s five if I do negative 5 we also get 5. that’s the absolute so we can also round let’s say x equals math dot round and let’s put in here let’s say 4.6 if I save that we get 5. if I put 4.2 and save it we get 4. now you can also round up or round down so for instance let’s do a round up and that’s going to be with the seal method so it’s going to be c e i l like ceiling and let’s put in 4.6 or I’m sorry let’s put in 4.2 and if I save it still goes to 5. okay so this will just round it like normally and then this will always round up so even though it’s 4.2 it’s rounding up to five now you can do the opposite and round down with the floor method so if I were to do math dot floor obviously that’s going to give me 4 but if I even if I do like 4.9 and I save that’s still going to give me 4. so these are pretty common seal and floor I use those in a lot of different situations um another one is pow so it will return the value of our number raised to a specific power so let’s say math Dot pow and let’s say we want to do 2 raised to three then we get eight okay we can also do the Min and Max so let’s say x equals math dot Min and what this will do is return the smallest of two or more numbers so if I do let’s say four and five and I save that’s going to give me four if I do another one pass in 3 that’s going to give me three and we can do the same thing with Max so if I were to do math dot Max and pass the same in we’re going to get 5 because that’s the largest of the three now a really common method is the random method so let’s say x equals math Dot random all right now if I run this what it gives me whoops it should be uppercase if you just use lowercase it’s going to look for uh just a variable called math so you have to use uppercase so what this will do is you’ll see I’ll keep reloading the page and every load it’s going to give me just a random decimal between 0 and 1. now that’s usually that’s not usually what you want usually you want to get like a number from say one to ten or one to a hundred so what you would do and what you’ll see a lot of let’s just um let’s use a variable of of Y here so I’ll say let y and we’re going to set that to math Dot random and then if we multiply that by 10 let’s see what we get we want a console log actually let’s just use x I don’t know why I did that okay let’s just do that now what that’s going to give us is a decimal between 1 and 10 right so if I keep reloading here actually I’m sorry not one and ten zero to nine now if I want it to be a decimal between 1 and 10 then what I would do is add 1 to this so let’s just put a plus sign here and then we’ll add one now it’s going to be one to ten let’s see if I can get 10. there it is so it’s going to be 1 to 10 as a decimal now what you want to do to make this a whole number is just round it down so we’re going to say math dot floor and we’re going to surround this whole thing and there we go so now we’re going to get a number between 1 and 10. if you want it to be between 1 and 100 we could just do that okay so you’ll see this this exact thing you’re going to see quite a bit because there are many times in programming in general where you need a random number and like I said there’s other methods on the math object if you want to check those out you can we might be looking at some of them later on but in the next video what I want to do is give you a little challenge that involves numbers as well as generating random numbers with with math.random all right so we’re going to do a little challenge here now keep in mind any challenge that I do it only involves stuff we’ve already worked with so I’m very limited with the types of challenges that I can create like I can’t have you guys create a function or anything because I haven’t gone over functions yet so some of these might be a little strange but it’s it’s all I could come up with with what we’ve gone over so far so basically what I want you guys to do is create a variable called X that is a random number between 1 and 100 along with a variable called y that is a random number between 1 and 50. and then I want you to create a variable for the sum the difference the product the quotient and the remainder of X and Y all right and then log the output in a string that shows the two numbers of X and Y along with the operator and result so basically you should have some variables like this that when you log it actually shows something like this 31 plus 15 equals 46 and along with the difference product quotient and remainder for a remainder you can use the modulus operator and then as far as hints the math.random function returns a floating Point pseudo random number in the range of zero to less than one so basically a random decimal and then the math.floor function will round a number down to the nearest integer so we talked about all that in the last lesson so go ahead and pause the video and see if you can just do this go ahead and create like I said X and Y random numbers between these ranges and then have these variables output these strings with the actual equation okay so let’s go ahead and get started so first thing I’m going to do is create my variables let’s say const and we’ll do x equals and remember X should be 1 through 100 a random number and Y should be one through I think it’s 150 I said I say 50 or 150. I think it was 150. so let’s say math dot floor because remember we want to round this down if we don’t use math.floor it’s going to be a decimal in fact let’s just let’s let’s do without it first just to see so we’ll say math.random and I’ll just log stuff as we go so we’ll say console log X and we get just a random decimal that’s going to be less than one basically and then if we want this to be between 1 and 100 what we could do is multiply it by 100 and that’s going to give us what 0 it’s that’s going to include zero so we want to do plus one if we do that then it’s going to be one between one and a hundred but it’s a decimal so that’s why we need to math.floor and round it down all right so now we have a number between one and 100 and then y I’m just going to copy this down Y is going to be between 1 and 150 so we’ll change this 100 to let me just check that did I say 50 or 150 oh I said 50 all right so we’ll change that to 50 and if we log X and Y then we’re going to get random numbers first one’s going to be 1 100 second is to 50. now we want to create variables that will show whatever X is plus whatever Y is equals whatever it equals we want to do the same for the difference in product and so on so what I’ll do is create a variable called sum and we want to get the value first so let’s say X Plus y and we can log out here some so we get 19 right so it’s just generating random numbers and adding them now let’s create another variable I’ll call this some output and by the way if you did something completely different as long as you get the same kind of output that’s absolutely fine there’s so many ways to do this so I’m going to set that to a template literal and in here I’m just going to take X and then say Plus and I’m wrapping these because they’re variables so I’m wrapping them in this money sign curly braces and then let’s say equals and then whatever the sum is okay and then let’s do just a console log because I want to log them all out we’ll say const output or console.log sum output and we can get rid of this and now you’ll see we get 34 plus 12 equals 46 which I think is true if I reload 19 plus 28 37 plus 3. all right so we we get the addition working now we’re going to do kind of the same thing for the difference let’s say this will get some or get the sum and what we can do is just copy this whole thing here and let’s say get the difference and let’s do we’ll call this um diff and we’ll do subtraction let’s say this is going to be our diff output and then this will be minus this will be diff and then diff output okay so if I save that then we get 78 minus 43 equals 35. all right now let’s go ahead and do the product so let’s call this um prod so like I said you just have to have the same time the same output not the same numbers obviously because it’s random but the same kind of output it doesn’t matter how you format this it’s still correct so prod output let’s do that and then that’s going to be the product and then this will be prod output there we go and then we want what else the quotient so we want to do division say quote q-u-o-t output and that’s going to be division so slash and quote and quote okay so we get 68 divided oh that’s not right oh I have a plus sign here make sure that we change that so 1 divided by 12. so we might get decimals here but that’s fine all right now the last one I want to do is the remainder so let’s say get the remainder and I’m going to use RM for the variable and then let’s change the plus to a modulus operator which is the percent sign we’ll say RM output and let’s make sure we change that to the percent sign this is going to be RM and then we want to log out the RM output and there we go so 543 modulo 5 is 3. good now like I said I know that this this is kind of a weird challenge so congrats if you got it but if you didn’t really understand it I I understand that because I only had so much to work with you know I couldn’t have you guys do something that I didn’t explain yet so that’s it in the next two videos the last two videos of this section we’re going to look at dates and times because those are something that are really important and in most areas of programming especially in web development where you have different resources like users and blog posts and all that and you want to have dates so you sign up dates and post dates so something that’s pretty important so we’re going to look at that in the next video all right guys so date dates and times are important in programming and JavaScript has a date object that represents a point in time and lets you do some basic operations on it so basically we can instantiate a new date object with the new keyword so I’m just going to create a variable here just so I don’t have to keep creating new ones we’ll just use this D variable and let’s set D to a new date now if I do this and I console log D you’ll see down here we get Friday October October 28 2022 it has the time it gives me the the time zone now this if we look at the type of this so if we say type of D we get object so the data is an object basically anything that’s not a primitive type is going to be an object now you can turn this to a string so I’ll say d dot to string if I do that then that’s going to be a string all right now if we want to set a specific date what we could do is say new date and then in here we can pass in a value so let’s say we want to do 20 20 we’ll do 20 21 and let’s say 6 10. and if I save that you’re going to see it’s Saturday July 10th now this might be confusing because we use 6 here but yet we’re getting July which is the seventh month so the caveat is that the month is zero based or zero index so if I put a 1 here then we’re going to get February if I put a 0 here then we’re going to get January okay so keep that in mind now if you want to add a time we could keep adding on to this let’s say we want 12 so that’ll be the hour and then we have and you can see right here we have the hour and then we can do minutes seconds so let’s say 12 for the hour we’ll do 30 for the minutes and 0 for the seconds if I save that you can see now we get 12 30. now instead of passing in arguments like that you can also pass in a string so are many different types of strings I should say formatted in many different ways so if I do a string so quotes here 20 21 let’s say Dash zero seven and let’s say 10. if I save that then we’re going to get July okay so set this is going to be correct so 7 is July if we do it like this and we pass in the separate arguments then the month is going to be zero based and if I wanted to add the time there’s a few ways I could do it I could do T and then let’s say 12 colon 30 colon zero zero if I do that now you’ll see the times 12 30. I could also do it this way so let’s clear this up and I could do let’s say 07 slash 10 slash 2021 and then I could do a space 12 30. like that and we get the same thing now there is a known issue if you use if you use hyphens and you use the year first then it could be off by a day due to the time zone so if I do let’s say do a string of 20 22 and let’s use hyphen so I’ll say 0 7 and 10. and then save that you’ll see it actually says July 9th even though I said July 10th so keep that in mind if you do the year first and hyphen it might be off by a day if your time zone is not set um if you put the month first it should work so if I were to do like seven 10 22 which is you know in the US is how we format dates then that does say July 10th and I’m going to put a link here to a stack Overflow that kind of explains why this uh why this happens so the next thing I want to look at are timestamps so the Unix timestamp is a system for describing a point in time and what it is it’s an integer that represents the number of seconds that’s elapsed that’s passed since the date of January 1st 1970 which is an arbitrary date so that that time stamp is expressed in milliseconds so or I should say the timestamp in JavaScript is expressed in milliseconds now you can always get the time stamp by using let’s say d so by using date dot now like that so if I save that we’re going to get the milliseconds that have passed if I reload you’ll see it’ll just keep updating right so that that gives you a way to always be able to mark an exact you know millisecond in time and we use timestamps for different things and we’ll probably use them throughout the course now to get a time stamp of a specific date you can use the get time function or method or you could use value of so for instance let’s say d equals and we’ll create a new date let’s just say we’ll do we’ll do the same thing seven we’ll do 10 in 2022. okay and then I’m going to get the time stamp by saying d dot get time actually I want to I want to log that so let’s how should I do this let’s set that to D so we can see that logged all right so this is the exact time stamp for this date now I didn’t put a time in here so we might want to do that so we could do like let’s say 12 30 0 0. okay so that’s always going to be that exact time stamp and then again you can also use value of so if I say d equals D dot value of and save I get the same thing if I want to get the exact time stamp for right now this date and time I could just clear that up and save and obviously that’s going to keep changing okay as time moves so you can also create date objects from a time stamp so let me just grab this right here which was a couple seconds ago and then I’m just going to say d equals new date and just like we can put in arguments or we can put in strings we can also put in a time stamp and then let’s save that you’ll see it’s October 28th and it’s going to be nine o’clock 49 seconds that’s what this time stamp represents right now it’s 901 okay so that was about a minute ago so let’s see the JavaScript timestamp is expressed in milliseconds if you want to convert it to seconds then what you could do is and just ignore the D equals for all these the only reason I’m setting it to the D is just so we can log it and see what what these actually give us but we could just do math dot floor and then we’ll take the date dot now which will give us the the time stamp of right now and then simply divide it by a thousand because there’s a thousand milliseconds in a second we save that and that’s the timestamp in seconds okay just remember in JavaScript by default the timestamps are milliseconds so in the next video I just want to look at some of the different methods that we can use on date objects and we already looked at the get time and value of but there’s a bunch of others as well that we’re going to look at all right so in this video we’re going to look at some of the methods on the date object now I just want to mention I I know that this isn’t the funnest stuff in the world but it’s really important to understand the basics and the fundamentals before moving on to you know building projects manipulating the Dom and fetching data and all that okay we’ll get to that but I think it’s important to know the basics so what I’m going to do here is just create a variable for our output and then I’m going to initialize a date variable so we’ll say new date and I’m just going to use today’s date so I’ll leave that I’ll leave that empty the argument’s empty and then let’s just do a console log of x now I know this might be a little confusing this new keyword we’ll get to that later we’re going to get to object oriented programming and get deeper into JavaScript but for now just know that what we’re doing here is we’re instantiating or initializing a date object into this D variable okay now with like the math object that we used a few videos back we would just do math dot whatever square root and we use the math object directly in this case where instantiating a date object into this variable okay so I guess that that’s a good enough explanation for now we’ll get more into it later so we already looked at some of the some of the the methods such as tostring okay so if we do two string it will just give us a string representation of the date we also looked at get time and also D dot let’s say value of okay so those will both give us a time stamp of the date in milliseconds now if you want to get specific parts of the date we can do that so let’s say we want to get the the year so we’ll do D dot and then there’s a get full year method and you can see it gives us 2022. now if I were to change the date up here by putting in let’s say 20 we’ll say 2020 slash 10 12. if I do that then the year is going to obviously change to 2020. all right now we can also get the the month so let’s say d dot get month now look what happened here uh oh I used a colon so notice that it says nine and right now it’s October so this is actually one month behind so when you use get month just like the caveat when we use the the arguments the month is going to be zero based okay so if I were to make this date January looks let’s say one two twenty twenty now you’ll see I get zero for the month so just just know that that’s zero based what you could do is just add a 1 to this and then that will give us the correct month all right and then if we want to get the day of the month so we’ll say d dot and that’s going to be get date if I do that I get 28 today’s October 28th if we want to get the day of the week then we do get day okay so get day or I keep putting a colon so get day will give us the day of the week get date will give us the day of the month now we also have some methods that have to do with time like if we want to get the the current hours we can do get hours if we do that you’ll see I get 9 it’s 9 37 right now if we want to get the minutes we could do get minutes so 37 if we want to do seconds we can get seconds so pretty self-explanatory and then we can also get milliseconds so we’ll say d dot get milliseconds all right now there might be times where you construct a date from these methods so for instance if I wanted to do let’s say create a template literal with back ticks and then I could use this syntax to put in my whatever whatever I want to put in here variable any JavaScript expression but let’s say we want to get the full year and then I’m going to go outside of that the curly braces and put a hyphen and then we’ll do D dot get let’s say get month but let’s add a 1 to it and then we’ll do another hyphen and then we want to get the day of the month so we’ll do D dot get date and if I save that um what did I oh I forgot the parentheses on the full year and there we go so now we have a string representation of the date using these methods so I I found myself doing stuff like this in real projects now there’s an API that we can use for dates it’s it’s called intl dot date time format and it’s a more modern and Powerful way to format dates in a Locale sensitive way because obviously you know different places they they interpret dates and times in different ways so we can actually pass in arguments like en-us for the United States or whatever the Locale is so let’s let me give you some examples of that so we’ll say x equals and it’s going to be I so capital i n t l dot and then date time format okay and then I’m gonna put in my Locale which is en-us and then let’s do Dot format and then I’m going to pass in my date my D variable so if I save that I get this 10 slash 28 22. now if you’re in the UK this might look a little weird to you so what we could do is instead of en US I could say Dash GB and then it’s going to put the day first which looks crazy to me but you know every country every area is different to get your default Locale you could just pass in default all right so if I do that it’s going to go back to the US because that’s where I’m located now if you wanted to just get like let’s say the month I’m just going to copy this down you could add options in here so after the default I’m just going to put a comma and then open up some curly braces and we could say month say we want to get the month and then let’s say we want the long format so we’ll just say long as a string if I save that it’ll just it’ll give me October all right and I’ll show you some of the other options in a minute but there’s a shorter way to do this right now what I’m doing is calling the API and then I’m passing in the date which is our D variable but on that D variable you have a method called two Locale date string and if we do that or actually you can just use two Locale string and then we can pass in the Locale I’ll just say default and then I could pass in options like for instance if I want to do let’s say month and get the short and I’ll paste the link in here to the documentation where you can see how you know more about this API but you’ll see I get ocked okay so instead of having to do this intl day format and then pass in your date you’re just calling a method on your date object and getting the same thing now I’m just going to put paste in here let’s see I’m just going to paste in this and let me just set X to that so we can log it and if I save that we get Friday October 28 2022 at 6 49 11 am which is not correct that’s not my time zone I don’t know why I have Los Angeles here I want to do I think it’s new underscore York there we go so that’s more like it but yeah so you can do weekday now if you just wanted for instance the weekday you could just pass that in like that and you get Friday so this is a newer way of doing things rather than this up here using the this this date time format API and that’s what I would probably suggest using uh you know it’s more location specific and you can format your dates and get whatever you want from the date pretty easily alright guys welcome to section two in this section we’re going to learn all about two really important data structures in JavaScript and that is arrays and objects or object literals I’m going to show you how to create them manipulate them using specific methods Nest them and some other stuff now since this is the beginning of the course I’m not going to get into really Advanced operations yet I’m not even going to get into like high order array methods for those of you that know what that is or any kind of iteration or Loops we’ll do that a few sections from now I just want you to really understand how to create and work with arrays and objects alright so let’s get started all right so the first few videos in this section are going to be on arrays and then we’ll move to object literals all right so arrays are a special type of object in JavaScript they’re also a data structure and they can store multiple values so this is how an array is formatted you can see we have a variable called ARR and arrays are surrounded in Brackets so the values inside of an array are surrounded in Brackets and the values are called elements okay so the each one of these is an element in this array now elements can be numbers they can be strings booleans any data type you can even have arrays within arrays and when it comes to accessing the values or the elements within the arrays we can use the index so arrays are zero based every language I’ve ever used they’re always zero based so they start at 0 1 2 3 and so on all right so I’ll show you how you can access whatever element you want using the specific certified index okay so let’s jump into vs code and start to just mess around with arrays so I’ll go ahead and create an array I’m going to just call it I’ll call it numbers and I’m going to set it to some brackets and in here we’ll just put some random numbers okay and and these it doesn’t have to be numbers I’ll create another one with a different type in a minute but let’s go ahead and console log out numbers and we should see in the console our five values now you also see the index and remember a razor zero base so the first one is always going to be at the zero index now there is another way to create an array object so this right here we just did this is called an array literal okay but we can also use the array Constructor okay just like we have like the date Constructor we used a few videos back where we said new date we can actually do this we can say I’ll call this numbers to actually let’s do a string here we’ll call we’ll call this uh fruits and I’m going to set it to a new array okay it has to be an uppercase a so new array and then in here I can put whatever I want in my array let’s say apple so they’re strings so they do have to have quotes we’ll say grape and orange so either of these are fine right I’ll say fruit console log fruits and you’ll see we get the same type of thing just an array with our with our strings now you’ll probably use and see this more the array literal more than the array Constructor it’s just more concise but you could use either they both create an array object now if we want to access a specific item let me just create a variable up here to Output and we’ll console log X and then I just want to show you how to access a specific item by the index so we’ll say x equals and let’s say numbers and we’ll get the first one so that’s going to be the zero index and you’ll see that’s going to log 12. and I could use this in any expression if I wanted to do like numbers and then get the first one and then maybe add on to that numbers and get the one that the three index and I get 41. I could also use them inside of a template literal so if I put back ticks in here and I’ll say my favorite fruit is and then I can access fruits and then let’s say I want to get the uh we’ll say orange that’s going to be the 2 index because it’s the third one so it says my favorite fruit is we’ll say is an orange all right now there is uh and by the way you can have different types I know these are all numbers these are all strings but I could do this like I could say we’ll call this mixed and I could set that to an array with a number with a string with a Boolean value null so you can put different types in here just to show you that now there is a property on a raise called length and you’ll probably use that quite a bit because there’s a lot of times where you need to know how many items are are in the array so let’s set x equal to we’ll say numbers dot length and if I save that you’ll see we get five if I were to add a new number onto this then we get six okay so that’s how we can get the length now if you want to change of value like let’s say we want to change let’s use the fruits array let’s say we want to change grape to I don’t know pear so we’ll take the fruit and we know that that’s at the one uh two position or two index and then we can set that to whatever we want let’s say pair and then I want to log fruits so I’ll just set X to fruits so if we save that we take a look you’ll see that now pair is in the the two index so arrays are they’re inherently mutable you can mutate them you can change them and also the length property is not read only so we have uh what three fruits but I could say fruits.length and I could say that that’s going to be 2 and if I save now you’ll see fruits only has two so you can do that as well but I’m not gonna I’m gonna comment that out now let’s say I wanted to add on to the end now there’s methods that we can use to do stuff like that and I’m going to show you that in the next video but we could so if we wanted to add a fruit we know that there’s three in there so it’s the index 0 1 2. I of course I could do like three a hard-coded three and I could set that to I don’t know strawberry and then if I log fruits you’ll see strawberries on the end but you’re not always going to know how how many items are in the array also that’s always changing so what you could do aside from using a method which I’ll show you in the next video what you could do is set the index to the length right so if I say fruits.length and then set that to let’s say blueberry if I save that now blueberry will get added to the end and the reason for that is the length is always going to be one more than the last because it’s this starts at zero if we look at the length it’s one two three four five and if I wanted to add one on to the next that would be five right in fact I could copy this down kind of running out of fruits here but let’s say peach and now that will get added to the end okay but but more commonly you’re going to use a method there’s a method called push I’m going to show you in the next video that does the same thing all right so yeah I mean that’s kind of the basics of arrays of creating them and getting the length and and finding the the values by index so in the next video we’ll go ahead and look at some methods all right so in the last video we looked at some array Basics how to create them how to access values by index and so on now I want to look at some of the methods that we can use so let’s create an array you can put whatever you want in it I’m just going to put some random numbers all right and then I’m going to just log out the array so in addition to the values here if we if we go ahead and click this Arrow you see there’s this prototype chain and this has all the different methods that we can use on this array which is quite there’s quite a bit here so obviously we’re not going to go over all of them right now we’re going to go over some of the really useful kind of simple ones just to mutate the array and get values from it and then later on we’ll we’ll look at some of the more advanced stuff including high order array methods so let’s start off with push which will just put a value on the end of the array in the last video I showed you how we could do that using the length property as an index but what you would probably do is just push on to it so you would say array dot push and then let’s say we want to add 100 and now you’ll see 100 gets added on to the end now if you want to take the value off of the very end off the last element then you would use the pop method so array dot pop and we wouldn’t pass anything in because it’s just going to pop off whatever is on the end now you’ll see that 100 is gone okay if we want to do the opposite and add on to the the beginning then we can use the unshift method and let’s say we want to add 99 now you’ll see 99 gets added to the zero index and if I want to take take it off of the beginning then we would use shift so array.shift and now 99 is gone okay we also can reverse the array with the reverse method pretty self-explanatory so now 15 which was at the end is now at the beginning now these methods that we just looked at these are used to manipulate the current array right so when we console log the array after they go through these methods it’s different right now it’s reversed and so on we did add some stuff on but then we took it back off so the next batch of methods I want to show you are ones that we can use to get something from the array either get a value from it or just get some information from it so I’m going to create a variable up here just like we’ve been doing just for our output and then let’s console log that variable and I want to show you the includes method which will allow you to to check and see if a specific value is in that array so I’m going to say x equals and then array dot includes and let’s see if we if we pass in 20 which 20 which we know is in there you’ll see it gives me true so you’re always going to get a true or false from this based on if the value is in there now if we put like 200 which we know is not in there then we’re going to get false all right so the next one I want to show you is index of and what that does is it’ll give you the index of a specific value so if I do let’s say index of and let’s pass in one of these values we’ll do 15. and I save that we get 0. now the reason it’s zero you can look up here and and it’s not zero here obviously but the reason it is is because we ran this reverse okay so the script runs top to bottom so since it’s reversed then it’s put in the zero position so what I’m going to do is just comment out these ones that we did that will that actually change the array just so we’re working with the same array we’re looking at up at the top all right so now if we look at the index of 15 it’s at four if we look at the index of 34 that should be the first one which is zero now if you put something in here that doesn’t exist like 340 you get a negative one okay so a lot of times you’ll you’ll run this through an if statement and just know that if whatever you pass in here is not there it’s going to give you a negative one now the next two I’m going to show you are pretty similar it’s slice and splice and both of them will return selected elements in the array so I’m going to start off with slice and I’ll kind of show you the differences as we go so array dot slice and what this takes in is the first is going to be the start index so where do I want to start in this array let’s say we want to start here which is the one index so we’ll pass that in now if I don’t pass anything else in what that’s going to give me is that value and everything after that as you can see here so 55 and everything after let’s say I want to get just um just 55.95 and 20 so that and the two after so then I would do one two four all right so how that works is we specify the one index and we want to go to the 4 so that’s going to be 1 2 3 and we stop at before the four okay um now this is this is returning this array okay the three that I selected into this x variable it’s not actually changing the array if I log the array in addition to that you’ll see it’s unchanged okay so keep that in mind about slice now splice you can do kind of the same thing but it does manipulate or it does change the original array so if I say x equals array dot splice and the the arguments we pass in or I should say the second argument is a little different the first is the start index just like with slice the second is the number of elements that we want to go over so let’s say I’m starting at one which is 55 and I want to go over four so one two three four I should get 55 to 15. so if I do 4 here and I save now look what we’re logging we’re logging X which is what we basically plucked out one to one and then four over so 55 to 15. now the array that I’m logging only has 34 in it because I basically plucked the rest out okay so slice doesn’t do that it doesn’t change the initial array splice does not only are you taking it out and putting whatever into the variable one one to four but you’re also changing the array so you’re not only getting the values you’re deleting them from the initial array all right now if you just wanna let’s say you just wanna delete one item then you can let’s comment that out so that we have our initial array what you could do is say x equals and then say array dot splice and let’s say we want to get rid of the 20. so we know that’s zero one two three so I’m going to put in the start at 3 and just 1. I only want to take out one and I’ll save that and now you can see we have the 20 in X so it’s set to X and then the array that we’re logging doesn’t have 20 in it anymore because we took it out so that’s how you can remove a single element from an array now the last thing I want to show you is how you can chain methods so I’m going to set X here equal to and let’s just comment out the splice because we know that that that changes our initial array and let’s move this down here so I’m going to set x equal to array and then I’m going to use slice here so slice let’s say one and we want to go 4 over from 1. so that’s going to basically give us again it’ll give us 55 through 15 right if I save this as it is and we look at the console log of x we don’t need array anymore if I look at the console log of x we get 55 well actually it’s I’m sorry I want to use splice if you use slice it’s only going to give you the three because it goes to the 4 index splice will actually go four over and then what I want to do is reverse that so I’m going to do dot reverse and if I save that now you’ll see it gives me that array that splice created and then reversed it if I wanted to change that to a string I could do two string and if I save that now I have it as a string and then I could use a method on a string remember the Char at so Char at you basically put in an index and it will give you that character so let’s say zero save that and I get one okay because the first one was 15 the first number so you can chain on methods like this and it’s not just with arrays as you can see it’s with strings it’s with anything anything that makes sense I mean it depends on what the method returns this splice we know that returns an array and I can run reverse on an array then I can turn an array into a string and then I can get a character from a string if I just run Char at on the Reversed array that’s not going to work it says reverse Char at it’s not a function okay what it really means is it’s not a function on whatever where we’re putting it on if I change that back and it’s a string then it is a function that works all right and you’ll see you’ll see chaining like this all throughout JavaScript so in the next video I want to get a little more uh acquainted with arrays so we’re going to look at things like nesting and concatenation with arrays we’re going to look at something called the spread operator and we’ll go from there all right guys so we’re gonna mess around a little bit more with arrays so I want to look at nesting concatenating and the spread operator and a couple other things so nesting an array is just it’s basically just having an array as an index inside of another array so let’s go ahead and create two separate arrays here I’m going to call this one fruits and we’ll put in here apple pear and let’s do uh Orange all right so that’s our first one and then we’ll do berries and yes I know berries are fruits so let’s say strawberry and blueberry and raspberry so we have two separate arrays now if I wanted to I could take fruits and we looked at the push method in the last video which will add something onto an array and let’s say we want to add on the berries array and then we’ll go ahead and console log fruits and let’s see what we get so we get an array with four items the first three are apple pear and orange and then we added berries which is another array so we have an array within an array so that’s how we can Nest them and you can go as many levels as you want now to access something in a nested array is pretty easy basically we can let’s let’s set this to an output variable so I’ll say let X and then let’s log let’s log X and we’ll say x is equal to and then fruits and let’s say I want to get blueberry which is nested in the the nested array so first of all I want the three Index right because it’s 0 1 2 and then we pushed on as the three index the whole berries array if I just log that what I get is the nested array if I want to get blueberry that’s going to be the one index on the nested array so I would just open another set of brackets and then put a 1 and that will give me blueberry all right now let’s say I wanted to create a whole new array called all fruits and I want to Nest both fruits and berries and we’ll just set X for now we’ll just set it to all fruits just so we can log it out and it’s an array with two items and both items are arrays okay so we just nested those two arrays and if I wanted to access let’s say strawberry I would say all fruits and I want the second array which is at the one index and then I want the first item in that array which is at the zero index save that and we get strawberry all right so hopefully that just helps you understand that you can Nest arrays inside of arrays as many levels as you want if I had a third level I could then access whoops I could access something within that you know so it you can Nest as far as you want now that’s nesting we can also concat arrays which is different it’s not to putting the array inside the array but it’s taking the items from one array and basically adding them into a different array okay as separate items on the same level so to do that we can use the concat method there’s actually a few ways to do it but concat is one of them so I can say fruits and let’s say we want to do Dot concat actually let’s comment this out because I want these to be two separate arrays again and yeah then the rest doesn’t really matter comment that out as well all right so I want to take fruits and then I’m going to concat onto that berries and let’s save that what we get is one single array that has everything from fruits and then everything from berries so the berries here they’re not put in as a as an array a nested array they’re just put in alongside of the rest of the fruits so they’re concatenated just like we concatenate strings with the plus sign we can concatenate array items using this method now that’s one way of doing it the other is using the spread operator and I’ll I’ll have comments throughout this I know I’ve said that a bunch of times I just don’t want to take the time to write comments for everything so the spread operator which is represented as three dots and this can be used with arrays as well as objects in fact you’ll probably use it more with objects and I’ll show you how to do that later but basically what we can do is let’s say we want X and instead of using concat what I could do basically what we did here was we created an array and then we put two arrays inside of it well let’s say I just want the items that are in fruits and berries not the actual array itself then we would use the spread operator with fruits and then the spread operator with berries and now I’m going to log X which is this right here we get the same exact result that we got with concat it just took the items from both arrays and put them basically combined them all right if I took the spread off of berries and I save now berries is going to be an array all right but there’s going to be a lot of times where you you want to take something from one or one array and spread those items across inside of another array so that’s where the spread operator comes in and same thing with objects but I’ll get to that in a little bit now there’s also a method we can use to flatten flatten flatten arrays and what I mean by that is if we have an array that has nested arrays let’s do this one two and then I’ll have another array here with three and four and then we’ll do five and then let’s do another array with six and seven and then eight all right so I have some nested arrays in here right if I set uh if I console log array then you can see that we have two nested arrays in here now let’s say I want to flatten this and just make it all one array that has one through eight for that let’s say x equals and we can set we can do array dot flat and now if I log X and I save that you’ll see now we just have a single array with one through eight so it just flatten this there’s no more nested arrays all right so that’s pretty much it for uh for some of the methods on the array itself now I want to show you some static methods that are on the actual array object um let me just put a comment in here we’ll say static methods on array object and what I mean is if we say capital A array and then dot there’s some methods we can use the first one I want to show you is is array so what this does is it checks to see if something is an array and I’m just going to set this to X so let’s say is array and we’ll pass in fruits and if I console log X we’re going to see true because yes fruits is an array up here if I were to pass in like a string then we’re going to get false so there will be some times where you have data structures that might act like arrays but aren’t quite especially when you get into like the Dom there’s like HTML Collections and things like that where you will you want to check to see if it’s an actual array and this is how you can do it so that is is array the next one I want to show you is from which will create an array from an array like value so if I say x equals and then array Dot from and this again this is pretty useful when it comes to like HTML collections or node lists or whatever but let’s put in here a string of one through five and let’s see what that gives us what it gives us is an array so it takes the string of one through five and gives us an array that has one through five in as an element okay so that’s from and then we also have uh of array dot of which will create an array from a set of values so maybe you have some variables where you want the values to all be inside of an array so I’ll just do this const a equals one V equals 2 C equals three and then I could say x equals array dot of and then we can pass in here A B and C if I save that it’s going to give us an array with one two three so basically just an array of the values of these variables and I know this is this might be a little Advanced for right now you might not be able to kind of visualize what you would use this for yet but I just wanted to throw some of this stuff in here so in the next video I want to test your knowledge or test what we’ve gone over with a couple fairly simple array challenges all right guys so now I’m going to give you a couple challenges and if you don’t get the challenges don’t worry about it I’m not that great at doing challenges where I can’t use resources and stuff like that either a lot of developers aren’t so don’t take it to heart if you can’t do it on your own now the first one I think is pretty easy I think a lot of you will get it so basically I just want you to create an array that has numbers one through five and then I want you to mutate that array using some of the methods that we’ve talked about and turn it into this which is six through zero all right so there’s just a couple methods that you can use I’m not going to give you any hints because this one’s pretty easy I’d encourage you to try to remember the methods rather than go back and look but if you have to look that’s fine too and then the second challenge is to combine or concatenate array one and array two but have the result not have the extra five because if you just concatenate these two you’re gonna have one through five and then you have another five through ten so I want you to concatenate but then take out the extra five and as a hint there’s many ways to do this but you can think of the concat method or the spread operator as well as the slice or splice methods and I’m going to give you two two solutions all right so pause the video now if you’re going to try this out and then just come back all right so let’s go ahead and do challenge one so we’re going to have an array with just one through five oops all right equals and then the result that we want to get is going to be an array that is six five four three two one and zero so that’s what we want the result to be so let’s console log array now there’s a couple methods that we need to use to achieve this hopefully you could remember them and not have to look back but if you did have to look back that’s that’s absolutely fine but we’re going to take the array and there’s a couple ways we can do this and there’s a couple different orders we can do this in so we could reverse it we know that you know this is is counting backwards so let’s say we want to reverse the array if I save that then we get five four three two one now we want to have a zero on the end so we could take the array and then we could push onto it a zero let me save that now we have five through zero and then to add on to the beginning we can use unshift and we can add on to the beginning a six and that’s it so pretty simple now you could have did it in a different order like you could have let’s save that you could have firsted the push so we could push a six on if I save that we get one through six and then you could do the unshift which pushes on to the beginning so you could put your zero and then you could do your reverse like that okay now you’re not going to be able to chain these because like push what that returns is it just Returns the number you push onto it so if I try to like uh if I try to do this some of you might might have tried this you know that that’s not going to work it says unshift is not a function and the reason is because this actually returns a number or it should let me just show you if I were to set let’s say let I’m not going to keep this but just to show you what this actually returns yeah Returns the the number six so you can’t chain those methods all right so that is my solution if you had a different solution and it worked then that’s that’s fine but let’s do challenge two so we’ll go ahead and say challenge two and this is going to be to concatenate these two arrays let’s say array one and that’s going to be one through five and then const array 2 is going to be 5 through 10. and then what you needed to do is concatenate these two arrays but they both have five so you need to get rid of that five and I’m going to give you two different solutions in each each one is in kind of the opposite order so let’s say solution one and I’m going to create a new array called array three and take array one and well basically what I’m going to do is slice that not slice the five out but slice these the ones that I want out and put that into array three so if I say dot slice and remember slice takes in the start index which I want to start at the beginning because I want one through four and then I’m going to put in 4 as the end if I save that oops we need to log this out array 3. if I save that now I have one through four in this array 3. so now what I need to do is basically just add the rest of this on right because I have one through four so I’m going to do that by chaining on concat and I’m going to concat array 2 and if I save that now I have 1 through 10 and there’s no double fives so that’s the first solution the second solution is kind of the the opposite of way around first I’m going to concatenate it so I’m going to say const array 4. and we’re going to use the spread operator here so let’s spread across array 1 values and let’s spread across array two values and if I were to console log array 4 you’ll see I’ll get 1 through 10 but I have my double fives here which I don’t want so then what I’ll do is use splice so I’ll take array 4 and then splice and I just want to take out one of those five so I’m going to start at the 4 index which is 0 1 2 3 4. so right here and I only want to take out one which is that that one so I’m going to put 1 as a second argument and then if I console log or A4 you’ll see I have one through ten and now that 5 is gone so two different approaches they both use different methods but they have they have the same result and you’ll see a lot of that in not only JavaScript but all programming all right so that’s it in the next video we’re going to look at object literals okay so now we’re going to get into another data structure and another type of object in JavaScript which is an object literal so basically these are key value pairs so I have a an example here we have a variable called person and then in curly braces we have just key value pairs that are separated by commas so basically we have the key on the left side then we have a colon and then we have the value which can be a string a number Boolean whatever and these are Keys these are values these are also called properties like this is the name property this is the age property and so on so let’s jump into vs code and let’s start to to work with objects so I’ll go ahead and just create the same one we just saw so we’ll say person and I’ll set that to a set of curly braces and then inside there we’re going to have a name let’s say John Doe and then we’ll do an age of 30. and we’ll do let’s say is admin and that will be a Boolean so we’ll say we’ll say true okay now as far as accessing data from this object first of all is just console log the whole thing see what we get so same thing just the key value pairs we also have our prototype chain which has some methods on it there’s a lot that we can do with objects in this section I’m gonna just go over some of the the basics and some of the easy stuff and then later on we’ll get into more complicated ways of working with objects now to access a specific property from an object we use the dot syntax so I’ll go ahead and actually you know what let’s create our X variable because there’s a few things I want to log out so let’s just do that and then let’s set X to person and then to access the name for instance I can say person.name now we can also use bracket notation so for for example I could say person and then I could use brackets and say I want the age I’m sorry this needs to be a string and I get 30. so this you’re going to see this a lot more the the dot syntax rather than the brackets but you can do it this way now let’s say we want to have an object within an object like maybe an address with some Fields so let’s say address and then we’re going to set that to another set of curly braces and then here we’ll have the street say 123 Main Street and then we’ll have the city let’s say Boston say for the state will do mass now if I want to access let’s say the state what I would do is say person Dot and then the address and then the state if we do that then I get Mass we could also have arrays in here like so if I wanted to do let’s say Hobbies set that to an array and we’ll say music and sports and then if I wanted to access that array I could of course just say person dot hobbies and that will give me the whole array if I wanted to access let’s say the first item or element in the array then I would use of course my my brackets just like I would with any array and that gives me music now we can also update properties so I can say person dot name and I’ll set that to let’s say Jane Doe and then if I log X we’ll just set it to person and you’ll see now the name is no longer John Doe it’s Jane Doe if I wanted to update let’s say is admin I could say person dot is admin or I could use this syntax is admin and what is it to begin with it’s true so I’ll set it to false and then if I log the person we should see is admin as false all right now if you want to remove completely remove a property from an object you can use delete so I could say delete and then person dot let’s delete the age if I do that and I log the object you’ll see there’s no more age now the next thing I’m going to show you is that we can add a function to as a property but I know we haven’t gone over functions so don’t worry about it if you don’t understand this but let’s say person and by the way I don’t think I mentioned you can not only change properties but you can add a new one like if I want to say person dot has children and set that to true and now if I save you’ll see that has children has been added okay so you can add properties as well now like I said about functions let’s say we want to create a function in this property called greet so I’ll say person.greet equals a function and this is just how we Define a function again I’ll get into this very soon and then I’m going to console log here uh template literal and say hello my name is and then I can actually access other properties in here with the this keyword so I could say this dot name and now if I want to call this function I’ll have to do person dot actually let’s just oh we’ll get nah we’ll just do that yeah person dot greet and we need to execute it with parentheses and you’ll see right here hello my name is Jane Doe all right so we we assigned a function to this greet property and we were able to access the name using the this keyword which I’ll talk much more about later now another thing that you can do but I really wouldn’t suggest it is when you’re creating your keys you can use like double more than one word so let’s say I wanted to use first name like first space name I wouldn’t recommend doing this but if you are going to do this then you can just surround it with quotes right so I could say first name and then set that to Brad and then we’ll do a last name so let’s say last space name and now if I want to access let’s say I want to access first name if I try to do this for a space name this is another reason I wouldn’t recommend doing this well right now it’s telling us person has already been defined so let’s change this to person two person two and it’s still going to give me an error because it says unexpected if I’d identifier name now if you’re going to do this again I wouldn’t recommend it using multiple words like this this should be in this form or even this form but if you do happen to come across this and you want to access it you have to use the bracket notation so you would do it like this first space name and you’ll see that will work all right so in the next video we’re going to look more at nesting objects within objects but I also want to show you how to use the spread operator with objects we saw how to use it with arrays but we can also use it with objects okay so now that you know what an object literal is I just want to get into a couple other things including using the spread operator with objects and some of the methods that we can use so and before we do that I just want to show you there is another way that we can create objects let’s say we want to create a to do object now we could do this which just creates an empty object and then we could add properties either in here or we could do like to do dot let’s say ID equals one right and then if we log that out let’s just create our X variable and then if we go ahead and set x equals two to do and we console log X we get an object with an ID of one now another way to do this this is an object literal but we could also use the object Constructor just like we did with arrays so we could say new object like that if I save we’re going to get the same thing so this line this is the same as just setting it to a literal and just an empty set of curly braces and I can continue to add on to this like if I say to do Dot name and we’ll set that to I don’t know buy milk and maybe to do completed not component completed and set that to false okay if we save that we take a look we’re just going to have our properties on that to do object now later on I’m going to show you how we can actually create our own Constructors for certain objects and we could do stuff like this like to do one and then set it to a new to do so you can create a custom Constructor for a custom to do object but we’ll get into that later on now I want to show you how to use the spread operator well actually before that let’s just let’s just go over nesting real quick I know we did in the last video but just to kind of remind you we could set person and then we could have address and then let’s say an address we have coordinates and maybe have a Latitude value of 42. something and then and then a longitude value of negative 71 dot something and then if we wanted to access the let’s say latitude we could do that by setting X to um person then we want to go into address then we want to go into chords and then we want the lat value all right so that’s nesting now as far as the spread operator goes it works very similarly to using it with arrays so what I’ll do here is just create two very simple objects it doesn’t really matter what you have for the Val the properties here but I’ll just do a one be two and then I’m going to create another object 2 and set this for the keys we’ll do c let’s say c 3 and then d 4. okay now if I create let’s say object three I could Nest those in here right so if I just pass in object one and then object two and then let’s just set X to just so we can see it we’ll set X to object three save that now what we have is an object that has two objects inside okay so the first one is object one second one object two now if I want to just take and you’ll you’ll find yourself doing this quite a bit in JavaScript if you want to just take the properties of object one and object two and put them in basically combine them into this single object three then you can just use the spread operator so we’ll just add three dots in front of each one and now when I log out object three we get all of these properties within both objects all on the the top level of object three because we we took them and spread them across all right now if I were to take the spread operator off object two and save you’ll see object one values are are on the top level spread across but object two is in there as a nested object all right so hopefully that makes sense now there’s uh there’s a few methods on the object object that we can use and one of them is called a sign and that does the same thing as the spread operator in fact the spread operator was introduced in es2015 before that you had to use object assign so let’s just say we want to create another object called object four and we’re going to set that to capital O object just like on the array object there’s methods there is here as well and the one we want to look at right now is called the sign so as the first argument we pass in is just going to be a set of empty curly braces that basically just gives us an empty object if I were to log obj4 you’ll see it’s just an empty object now if I want to add the properties from object 1 I would pass object 1 in as the second argument and if I save now you’ll see those are added to this obj4 if I want to take the properties of object 2 I would just add that as another argument save and now those get added okay so whatever I pass in here any objects I pass in here the properties of those are going to get assigned to this empty object okay so both of these lines do the same exact thing and it’s up to you on what you want to use the spread operator to me is easier and more concise and just more modern but if you want you can of course use this Okay so a lot of times we’re going to be dealing with arrays of objects anything any resources in the database like or from an API like to Do’s or users or blog posts you’re usually going to deal with arrays of objects for those resources so so let’s say um should we do here let’s say we want to do an array called to Do’s right so we’ll set that to an array and then in that array we’ll have our first to do so it’s going to be an object we’ll say id1 and then name we’ll say I don’t know buy milk again okay and I’m going to put a comma after that and copy it down a couple times and the second one second object is going to have an ID of 2 this will have an ID of three and here we’ll say I don’t know pick up kids from school and then we’ll have take out trash okay so now we have an array I’m yes an array of objects I’m going to set this x here to to Do’s if I do that we’re going to see our array of objects now if I want to access a specific object just like we do with any array we use our bracket syntax say we want to get the first one we use our zero index that gives us that object now if I want to access specific property like name I simply do dot name all right so those are arrays of objects now later on we’re going to get into iteration and looping and being able to you know go through each object and and do something to it or just display it but we’re gonna we’re gonna do that a little bit later now I want to show you a few other methods we have available on object so if you want to get all of the keys in an object and put those into an array we can use object keys so let’s say x equals object dot keys and what do I want to use this on let’s do the the to do object we created up here so say object dot keys and we’ll pass in the to do object and then we want to log X and you’ll see now we have an array that has the value of ID name and completed okay so it just took the keys from this to do object and put them into an array now there’s going to be times where you’re going to want to get the length of an object meaning how many you know how many properties does it have in it and we can’t use length on that like if I try to do x equals and let’s take our to do object and do length if I do that it’s going to say undefined so the way that we can get it is by first getting the keys and then getting the length of that so if I just take this and put that on there that’s going to give me an array right and we can use length on an array so we’ll simply do length and if I save we get three okay so up here you can see we have three and and I could have created an object literal as well so the next thing is uh if you want to get an array with all the values just the values we can use object.values just like we can use object dot keys so let’s say object dot values and we’ll pass in to do save that and now we just have an array of the values now if you want to get an array of the key value pairs you can do that with entries so let’s say x equals object Dot entries and then pass in our object save that and now we have an array with arrays that have the key value pairs and then the last one I’m going to show you is has own property which will give you a Boolean indicating if the object has a specific property so let’s say x equals and then we actually call this on the the actual object so for instance to do and then we can say has own property and let’s pass in name if I save that we get true because it does have a name property right if we put in I don’t know age and I save that then we get false because that to do object does not have a property of age so that’s it I just wanted you guys to get familiar with the spread operator and some of these these really helpful methods that you have on on your object so in the next video we’re going to look at something called destructuring and also naming because you do have a lot of properties inside of an object and sometimes you might not you might not want to do this because it’s pretty long I’m going to show you how you can destructure so that you don’t have to do as as many you know as much as this dot notation so we’ll get into that in the next video okay so now I just want to show you a couple things that you can do as far as naming and and destructuring variable names from object literals so first off if you’re creating an object where the key and the value are the same if the value is a variable then you don’t have to add both so let me show you what I mean if we have these variables here and let’s say I want to create an object so we’ll say const person and let’s say I want to set name or not name first name and I want to set that to the first name variable right so you would do that and then I’ll just copy that down and this one will be last name and this one last name and then we have our age okay so now if I come down here and do a console log of person Dot age and save that of course I get 30. so I’m setting the key of first name to the value of whatever is in the variable of first name if you do this and these are the same you don’t need to add the second one you don’t need to add the value you can simply do this get rid of the colon as well and now if I save that we still get 30. so it saves you some typing and uh and I just wanted to show you this because most most JavaScript developers will do this there’s no sense in in repeating yourself if you don’t have to so the next thing I want to look at is destructuring so basically what we can do here let’s say I wanted to get well let’s create another object so we’ll create a to-do object with an ID and let’s say title take out trash so if I want to create a variable of ID with the ID of that to do I could do this you know I could do that and then console.log the ID but what we what we can do is destructure properties from the object so we want to set this equal to the object itself and then any properties we want to extract or destructure are going to go into these curly braces so if I save that you’ll see I get one I get the same thing if I want to take out the name I can do that as well so you you can well let me log it so you can see so you can think of this as I’m sorry not name title the title and title so you can think of this as as pulling these variables out of the of the object and you can go multiple levels deep like let’s say we have a user in here and that’s an object that has a name so if I want to get that if I come down here and I destructure user I’m just going to log that for now and save that and you see that it’ll pull out the object to use this entire user object if I want to get the name or any other property what I could do is put a colon here open up another set of curly braces and we want to take the name from the user so now if I come down here I should be able to just console log name now another thing we can do is rename Properties or keys so let’s say I’m destructuring ID but let’s say I want to rename it to to do ID if I want to do that I can put a colon and then just do to do ID like that and then if I come down here and I console log to do ID I get one okay so this and this might might be a little confusing just keep in mind that when you use the curly braces you’re destructuring if you don’t then you’re just renaming now we can also destructure arrays and I know we’re talking about objects in these in the last few videos but I figured it’s relevant here to show you this stuff even though it does have to do with arrays so I’m going to create an array called numbers and we’ll set that to just whatever 33 and let’s do one more okay and I just want to put a comment here that we can destructure arrays oops that should be a comma all right so the way that we do this is we create variables for starting at the beginning for the first second third and so on all right so let’s say const and then the way we destructure arrays is going to be with brackets okay objects we use curly braces and arrays we use brackets we’re going to set that to the array name which is numbers and then in here I’m going to say first and second so what this will do you’ll see if I console log first and second it’s going to give me the first two elements the first two values in the array 23 and 67. and of course if I if I put third in here that would be the next one 33. now if you want to get the rest of the numbers and put them into a variable as an array we can use What’s called the rest operator now it’s a little confusing because the rest operator is is the same as the spread operator it’s the three dots but in this use case it’s often called the rest operator and the way we use that is instead of just putting third which would just get the next one we would do three dots and then a variable name oftentimes called rest and then what I’ll do here is log first second and rest now what you’ll see is we’re logging the first and second 2367 and then rest contains an array with the rest of the values in that array in this case is 33 and 49. if I put in 52 here and save that’s going to get added to the rest array and just to show you I can change this to anything I’ll just say we’ll say nums and then if I come down here and I do nums that’s going to give me the same thing but I’m just going to put that back to rest okay so I know it’s a little confusing spread operator rest operator it’s just when you use it in this instance or in this use case then you might see it called the rest operator all right so that’s it in the next video I want to talk a little bit about Json okay so since we’ve been talking about JavaScript objects I think that this is a good place to introduce Json okay which I get a lot of crap for saying it that way a lot of people say Json I say Jason but it really doesn’t matter it’s j j s o n now Jason is something that you’ll be working with a lot as a JavaScript developer and it stands for JavaScript object notation and it’s a lightweight data interchange format so it’s essentially a way of storing data in a simple human readable format now in web development especially in JavaScript we work a lot with with apis and you know apis to send and receive data to and from a server and several years ago XML which is extensible markup language was kind of the standard for sending data or getting data from a server but in recent years Jason has become the stand standard so you’ll very very rarely work with XML these days now Jason the syntax is very similar to JavaScript object literals which is what we’ve been working with now to give you kind of an example of an API that you may work with as a front-end developer you’re going to work with backend apis where you hit you know a URL and you fetch some data or you post some data and we’re going to get into all that later on apis and you know rest apis and stuff like that now just to give you an example GitHub has has a public API that we can use so I’m going to go to one of the URLs just to kind of show you an example of of some data we’ll get back so if we go to it’s actually API api.github.com and then we can go to slash users if I do that will get an array of like I think I think it’s like the first 20 users of GitHub so as you can see it’s an array of Json objects which are very similar to JavaScript objects right we have key value pairs now the difference here is that the keys are going to have double quotes around them as well and with JavaScript object literals we don’t have quotes around the keys and you have to have double quotes around the strings here as well numbers you don’t have to but strings you have to have double quotes around or it’s not going to be valid Json but this endpoint here API github.com users is an example of something you’d hit with with the fetch API which we’ll learn about later and you can make a request and get this data and bring it into your application you could even do user slash and then your username so I’ll put mine in here and then that gives me some information about my account my login my ID number it even gives me some other API URLs that I can hit to get other things all right so for example uh is the repos so this repos URL if I were to hit that end point I get an array of all my GitHub repositories okay so as Json objects so I just wanted to kind of show you an example of an API that gives us Json data now you can also have Json files like if I create a new file here and I’ll just say I don’t know to do dot Json the way that I would do this it usually a Json file is going to have an array of Json objects so you would have brackets just like in JavaScript and then each object would have curly braces but your keys have to have double quotes as well so say id1 this could be a number or a string and then let’s say title title say take out trash now vs code will automatically validate this like if I take those quotes off it’s going to give me an error if I hover over it says property Keys must be double quoted because it knows them in a Json file okay and then there are websites where you can validate Json as well you just paste it in and it will tell you if it’s correct but yeah it’s pretty much just a JavaScript object with some double quotes so what I want to do as far as JavaScript to show you how we can convert our objects to Json and the other way around so let’s create an object here let’s do something different we’ll do like uh which we do we’ll do posts like a blog post and we’ll set that to let’s say title say post one and this is just a JavaScript object literal so title actually let’s put an ID to so we’ll say id1 and then let’s put a body and I’ll just say this is the body okay so we have a JavaScript object right I can console log that post and if I want to convert this to a what we call a Json string there’s a Json object we can use so let’s say cons string so this Json object has a method called stringify so just stringify and Par so the two methods you’re going to be using quite a bit when dealing with this so stringify will turn an object into a Json string so I’m going to pass in here post and then let’s log Str and and notice it’s formatted differently it doesn’t have like the collapsible arrows and stuff like that it’s just a simple string okay and this is what you would send if you were sending data to a server this is what you would send okay now when you use like the fetch API or other libraries to make HTTP requests a lot of times it does this for you like you you can just send the post like this and it will automatically stringify it where you do end up using stringify and parse the next one I’m going to show you is with local storage and local storage is a way to store things on your client on in your browser and they can only store it can only store strings so you can’t store like an object like this so what you would do is stringify your object put it into local storage and then when you take it out you would parse it back into an object and we’ll we’re going to get all into local storage later so now that we have a Json string in the Str variable let’s parse that Json so we can do that and I’m going to put this in a new variable called obj and we’re going to set that to Json dot parse and then we’re going to pass the string Json string in there and then let’s go ahead and log obj and we’re going to get our initial post object literal okay so these are the two methods that you’ll be using quite a bit when dealing with this type of thing and then it doesn’t have to just be a single object it can be an array as well so if we say const let’s say posts and we set that to an array of objects I’ll just grab this one here and paste that in then we’ll put a comma and we’ll create another one and I’ll just change that to a 2 and we’ll say post 2. so now we have an array of objects let’s say down here const str2 and we’ll set that to Json Dot stringify and let’s pass in our posts and then if we log str2 you’ll see we have a Json string that has a couple array a couple arrays a couple objects inside of an array now one thing to keep in mind is if you have a Json string like this this Str right here you can’t take that Json string and then try to access like let’s say ID okay if I do that I’m going to get undefined all right if you need to access a specific property you first need to parse it so if I console log object dot ID that’s going to work but yeah I mean that’s that’s pretty much it as far as using JavaScript to parse Json strings or turning JavaScript objects into Json strings so in the next video we’re going to have just a pretty simple object challenge for you guys and then we’ll move on to functions and scope and things like that all right guys so I have a a challenge here for you that has to do with object literals and it has multiple steps but don’t get overwhelmed because it’s it’s pretty easy for those of you that already know the basics of JavaScript will have no problems with this but we’re going to take it step by step so I’m going to read step one you can pause the video and do it I’ll do it and then I’ll go to step two step three Etc so step one is to create an array of objects called Library so have a variable called Library set it to an array have three objects inside with the type the properties of title author and Status title and author Should Be Strings whatever you want whatever book title and author and then status should be another object so a nested object with the property of own reading and red which should all be Boolean values okay so do you if you own the book if you’re reading it and if you’ve read it so for all status set own to true and then set reading and red to false so basically you just need to construct an array of objects so pause the video now and go ahead and do that and I’m going to do that now as well so I’m going to create a library array here and then inside it says to do three objects with properties of title so I’ll just put that for now and then we also want author which is going to be a string and then we want the status which is going to be a nested object and status is going to have own which we want to set to true it’s going to have reading which we set to false and then red which we also set to false okay so I’m going to just copy this because we want three of these okay so we just want to make sure we had three and you can put whatever you want for the titles and authors I’m going to say the road ahead I’m just putting anything here and this is by Bill Gates and then we have the Steve Jobs biography by Walter Isaacson I think that’s ice palette and then we have Mockingjay and that’s by Suzanne Collins okay so here’s step one right we just created an array with three objects with the property specified so now let’s move on to step two so you finished reading all the books set the read value for all of them to True do not edit the initial objects at the values using dot notation so don’t just go in and change red to True here we’re going to come down here and set all of the the red values to true so you can pause the video and do it yourself but this is going to be pretty simple basically we just want to say library and there’s there’s multiple ways you could do this you could Loop through it but we haven’t gone over Loops or anything so let’s say library zero and we want to set status right and then we want to set red to true and we’re going to do that for all of them so let’s say one and two as well and then we’ll just go ahead and do a console log of library and if we take a look we should now see in status that read is true for all of these so read is true and status read is true so that’s step two step three is to destructure the title from the first book and rename the variable to First book so we went over destructuring and naming a couple videos back so let’s do that we’re going to go let’s just put a comment here and pause the video if you’re gonna do it on your own and say step two and this is step one okay so step three we’re gonna destructure so from the what was it the first destructs of the title from the first book and rename it to First book so we know the destruction object we use curly braces and we want to set this to the object name which is Library we want to destructure the title right so I’ll say title and then let’s console log title actually I’m going to get rid of this console log right here so I’ll save that we get undefined and that’s because we’re in an array it’s not a single object called Library so we want to get the first the first book if I save that we get the road ahead now to rename this variable we just use a colon so we can say colon and we’ll say first book and then we should be able to console log the first book variable and get the road ahead so that’s step three so step four is to Simply turn the library object into a Json string so you can pause the video and do that and that’s pretty simple say step four so we want to we’ll create a new variable we’ll call it Library Json and then let’s set that to Json Dot stringify and we want to pass in the library object and then we’ll go ahead and console log Library Json and now we should have our library as a Json string all right so that’s it I know that was pretty simple for those of you that already know JavaScript Basics but if you didn’t then hopefully this helped you out so in the next section we’re going to go ahead and start looking at functions and scope all right so now we’re going to start to get into functions which are really important part of any type of programming because you can create blocks of code that you can run anywhere and at any time so we’ll look at creating basic functions we’ll look at function declaration versus Expressions we’ll look at Arrow functions something called iffes or immediately invoked function Expressions we’re also going to look at scope which is really important in programming because this lets you know what what context your code is being run in if it’s the global scope or if it’s within a function scope or another type of block scope and then we’re also going to look at things like the execution context and the call stack which are might seem a little Advanced but like I said I want you to not only learn the syntax but understand kind of what’s going on under the hood in the browser what’s actually happening and execution context is something that I think you’ll benefit in learning now rather than you know two years down the road so it’s just the last I think two or three videos we’ll be talking about that stuff and you’re not gonna need to learn any any advanced code or anything like that in fact we’re going to look at very very simple code but just look at what is actually happening behind the scenes with the execution context with the call stack and so on all right so that’s it let’s go ahead and get started on functions all right so now we’re going to talk about functions and scope and I know a lot of you already understand functions and and that’s fine but I do want people that are new to JavaScript and new to programming to basically be able to start from scratch and learn what functions are and how to use them so let’s get started with some of the basics so first of all a function is it’s a way to group code together that you can run later you can run at any time and as many times as you want and it’s a way to make your your code more readable and easier to understand so to create a function there’s actually multiple ways and I’m going to show you multiple ways but for now we’re going to do kind of the the basic way to create a function and that’s using the function keyword so after that we can give a function any name we want let’s say we want to call it say hello and then we need to add in our parentheses okay now in the curly braces here is where the function body goes this is this is the code that will run when we run our function so I’m just going to have this function do a simple console log of hello world all right now if I save this nothing is going to happen because all I’ve done is defined or declared the function I haven’t run it to run it we have to put in the function name and then a set of parentheses so if I go ahead and save that and run it you’ll see that it’ll console log hello world so that’s that’s the absolute simplest function that you could write now when it comes to passing data into a function we do that with parameters okay and and there’s a difference between parameters and arguments a lot of times they’re used interchangeably which I think is fine but just to be really specific when you’re declaring a function like let’s say we have a function called add and when we’re putting in here the variables that we want to be able to be passed in like let’s say we want we want X and wire let’s be a little more specific we’ll say num1 and num2 so this function takes in two numbers these are the parameters okay that the function can take and then what I’m going to have this function do is just console log num1 plus num2 so it’ll evaluate that expression and log it to the console now when I call this function so I say add and then I pass in the numbers that I want to add let’s say 5 and 10. these are arguments okay when you’re declaring the function these are parameters when you pass in an uh a value here these are arguments but again people will say I’m passing in a parameter of five and I think that’s fine I’m not like you know one of those sticklers and just to be clear on the kind of the vocabulary when we run a function like this this is invoking a function or calling a function when we do this this is defining or declaring a function now most of the time when we create functions we’re returning some kind of value these particular functions that I just created they’re not returning anything they’re just simply doing a console log but usually we’ll return something so to give you an example let’s say function and we’ll call this subtract okay and this is going to take in again let’s say num1 and num2 and I’ll get to scope but just know that these variables even though these are the same it’s okay because they’re function parameters of in different functions so I can use num1 here and here I couldn’t use it like in the global scope I couldn’t create num1 and then create num1 again so in here let’s go ahead and return we do that with the return keyword and we’re going to return X not X num1 minus num2 now I’m going to go ahead and invoke this by saying subtract and then I’m going to pass in let’s say 10 and 2. now if I save this we don’t see anything in the console because we haven’t done any kind of console log what we did is returned uh the the result of this expression now I’ll get into why we return values in a second but just know that anything we do under this like let’s just console.log we’ll say after the return if I go ahead and run this you we don’t see the console log that’s because we’ve already returned we’ve already exited the function so it’s not going to run anything after an in vs code you can see it’s kind of a lighter lighter contrast now the reason we return something is because we want to do something with that value so in this case let’s say we want to put it into a variable so I can actually set let’s say right here we’ll say const and then say result equals subtract 10 from 2 or I should say 2 from 10. and then I can do what I want with that result so I’ll just console log it I’ll say console log result and now I get 8. I could also just console log the function I could say subtract and let’s say I don’t know 20 and 5. if I save that I get 15. all right so instead of console logging from here this this is going to hold whatever the value is it’s returned and there might be cases where you return with no value you just write return and that’s good for like um let’s say you’re you’re sending a request to a backend or an API and you’re updating something in a database and you’re not you don’t actually need to return anything you might just return with no value all right now in the next video I want to talk more about arguments and parameters I know I mentioned them here and and showed you you know the basics but I want to talk a little bit more about that in the next video all right guys so in the last video we saw that we can create functions and we can allow data to be passed in by creating parameters or params and then the data we pass in when we invoke the function are called arguments so I want to look a little more into that so let’s create a function here we’ll call it register user and let’s say it takes in a user which right now will just be a string and then I’m going to just return from this let’s say user and then I’ll just concatenate on and say is registered obviously in real life you would you would connect to a database and insert a user in this now but this is just for for example so we’re going to return that string and then I’m going to just console log register user and we’ll pass in a string of John and then in the console you can see we get John is registered okay so created a parameter of user we pass an argument of John now first off if it’s not obvious this user variable right here this is not available outside of the function it’s in what we call the function scope and I’m going to talk more about scope in a video very soon but just to clear that just to show you that if I console log user it says user is not defined so out here in the global scope it doesn’t see that user variable now if I were to console log register user without passing anything in even though I defined user you can see I get undefined as user because remember a variable that hasn’t been defined it has a data type of undefined and a value of undefined so what we could do to have a default value there’s actually a couple ways we could do that um the old way before es2015 actually let’s go in here was to have an if statement I know we haven’t gone over in conditionals yet but this is pretty simple we would just say if not remember the exclamation is basically the opposite so we could say if not user whoops meaning it didn’t get passed in then we could take that user variable and assign it so let’s call it bot and now if I save that and we run it you’ll see it says bot is registered now with the es2015 or es6 update there’s an easier way to have default parameters because you don’t want to have to do this for every parameter that you have so let’s comment that out and then up here what we can do is simply say user equals and then set it to whatever we want as the default and now ICDC bot is registered okay if I had another variable and I wanted to set it to a value I could do it just just like that just adding the equal sign so that’s default parameters let me just put a comment here so default params and then the next thing I want to show you are rest rest parameters and if you remember a few videos back when we looked at the structuring I showed you with arrays you can destructure values into variables and then you could use the rest operator to basically put the rest of them into an array and you can do kind of the same thing with your parameters or with your arguments so let’s create a function here we’ll call it sum and I’m going to use the rest operator here with a variable called numbers and that can be called whatever you want and then let’s just do uh I want you to get used to using return so we’ll just return from here numbers and I want to see show you what we get now since we use return we do have to just console log the function so we’ll say sum and then let’s pass in one two three and see what we get so it gives us an array with all of the arguments that we passed in okay and I could pass in just as many as I want here and it all gets put into an array called numbers okay a function scoped array called numbers now I know we haven’t gone over like for Loops or anything but I just want to show you that we could use a for Loop to take all the numbers that are passed in and then add them together so let’s go ahead and just initialize a variable here called total and we’re going to set that to zero and then I want to Loop through again I’ll I’m going to go over four Loops in depth later but let’s say const num so we’re going to say num of numbers so basically for each one of the numbers we’re going to call it num and then I’m going to take that total variable and I’m going to use the plus equals here so that I can add num onto each one after every iteration and then I’m just going to return the total okay so now if I console log sum and pass in one through five I get 15 because it’s just adding them all together okay if I add 6 21 if I add 100 121 and again this the body doesn’t matter I just want you to understand you can basically pass in unlimited number of arguments using the rest operator and that those all get put into an array all right now you’re not always going to get primitive values passed in as arguments in fact more often than not you pass in objects and arrays and stuff so let’s say objects as params and we’ll do we did register let’s do login user and say it takes in the user but this time it’s going to be an object so obviously you could use any of the properties that are on that object so for instance we could do a console let’s do a we’ll do a return so we’ll say return and I’ll use a template literal here and let’s say the user I guess yeah we’ll just put the user and let’s say that user has a a name property with the ID of and then we’ll do user dot ID is logged in okay and then down here what we could do is we could pass it in a few ways we could put it into a variable like this and we could give it an ID and then a name and then we could call login user and we could pass in that user and if I save actually we returned it so we need to actually console log it so if I do that we get the user John with the ID of 1 is logged in okay or you could pass it in let’s do another console log you could also just pass in like this let’s put the object and let’s say id2 and name Sarah and then we get the user Sarah with the ID of 2 is logged in so we can also pass in arrays let’s say arrays as params and now I’m going to actually create a function finally that’s semi useful so we’ll create a function that will get a random number from a specific array that we pass in and if you want to pause the video and try this on your own you can because we’ve already looked at how to get random numbers and stuff like that so you can do that if you want but I’m just going to create a function called let’s call it get random and it’s going to take in an array and then first thing I’ll do is is generate a random index for the array for the element that we’re getting because remember we access the element through indexes so let’s say random index and we’ll set that to math dot floor so we’re going to round down remember this from a couple sections back so we’re going to round down a random number let’s say math dot random that gives us a decimal between 0 and 1 so we want to multiply that by the length of the array okay so this is all stuff that we’ve looked at so that will give me a random index now I’m just going to create a variable called item and set it to the array and then the index is going to be random So Random index we want to use that here okay and then we’ll just return or we’ll just console log the item okay and then let’s just call down here get random and we just want to pass in an array and you can put whatever numbers you want in here we’ll do one through ten and you’ll see 9 if I reload 9 10 3 10 8 . so yeah it’ll just generate a random number that you pass in now remember the the the rest parameters that will give you an array of anything you pass in so another thing we could do here is just add on that and then automatically whatever we pass in gets put into an array so I could actually get rid of the brackets here and save and I should get the same result which will give me a random number between any of these numbers I pass in and I didn’t need to pass in an array because the rest rest operator will turn whatever I pass in into an array but I’m going to put it back to how I had it just because this is supposed to be showing you how to pass in an array all right cool so in the next video we’re going to look start to look at scope okay so in this video we’re going to talk about scope and in particular Global and function scope now scope it’s an important Concept in JavaScript and it refers to the current area or the context of a specific piece of code and there’s certain rules for what we can access in specific Scopes now global means just what it sounds like it means that your your Global variables are going to be accessible from absolutely anywhere in fact the browser has a window object if I go ahead and type in window in the console we’ll see the window object here that has a ton of methods and properties that we can access from anywhere whether we’re just in our Global page scope or if we’re in a function or in a block or whatever in fact alert the method alert is on that window object if I say window dot alert and I pass in here let’s say hello and I save that and run it then we’re going to see that pop up now since window is the the top most object it’s at the top level we don’t even need to do the the window dot we could just do alert which is what you’ll usually see okay um and then there’s other things like for instance we can do window dot inner width and that will give us the browser’s inner width so you’ll see down here it’s logging 455. and again we don’t need window but in this case on something like this on inner width I would keep the window but it’s it’s really preference but just to show you I could do it without it all right now we can access these these window object properties and methods from anywhere if I were to create a function and say run and then run that function and in here do let’s just do console log we’ll do window dot let’s say inner height which is another property if I do that it’s going to show down here my my window height is 136 and it’s measuring from here to the to the console all right now as far as creating our own variables in the global scope that’s really what we’ve been doing if if you’re creating a variable that’s not in a function or in a block or anything that’s in your Global scope so let’s say x equals 100 and obviously I can access it from the global scope if I do X I’m just going to also put a string in here that says we’ll just say in global save that we’re going to see 100 and in global now since that’s Global I can also access that in functions so I’ll say console log X and let’s say in function save it and you can see we can access it there as well if I have a block like an if statement which I know we haven’t talked about yet but just to show you real quick if I say if true so since I put true whatever I put in here is going to run I’ll do a console log of x and I’ll say in Block save that you can see we’re accessing it from there as well now functions have their own scope so what I’m going to do here is create another function called add and in here obviously we can access X I already showed you that we can create variables in our functions so we’ll say const Y and we’ll set that to 50. and then I’ll do a console log of Y and what we have to run it so if I save that and run it you’ll see that we’re logging Y which is 50. now since I defined this variable inside the function this is function scoped okay this is not a global variable if I go outside the function and I try to log y I’m going to get an error it says Y is not defined because it’s looking in the global scope it’s not going to go into this function and pull out variables and allow us to access them and of course since I created this this variable Y in this function I can’t go in this function and do it here either right if I do that now this error is running you can see at line 11 and that’s where I just did this console log all right so I’m just going to undo that and I’ll comment this out to get rid of that error now I can access the global variable X inside of any function I want so if I were to go right here let’s say console log X Plus Y and I’m going to get 150. all right now if I were to in this add function create a variable called X if I do that and save you’re going to see now we get 51 it’s adding this X and this y so what this is doing is overwriting the globally scoped x value and this is called variable shadowing now when you hear the term local scope that’s just that just refers to whatever scope you’re in whatever you’re talking about if we’re talking about you know this y variable right here then our local scope is this add function scope if we’re talking about this one then where the local scope is the global scope all right now that is global and function scope in the next video even though we haven’t gone over like if statements and loops and stuff like that which are blocks I think this is a good place to talk about block scope all right so we talked about global scope and function scope now we’re going to talk about Block Level scope and I’m also going to show you some of the differences between using VAR to create variables versus using Latin const because VAR is not Block Level scoped so I’m going to create a variable in the global scope called X and then I already showed you this in the last video that if we have a conditional which is a block and we try to access a global variable that’s fine right because Global variables we can access from anywhere now if inside of this block I create a variable let’s say Y and set it to 200 of course from here I could do like X Plus y that’s going to work but if I come out here and I try to do X Plus y that’s not going to work because y has not been defined on the global scope it’s defined inside of this block so it belongs to this block so I’m going to comment that out and I’m going to show you how this would work with VAR in a second but first I want to show you a loop example so you don’t have to understand for Loops yet to really see what I’m talking about here but I’m just going to create a simple for Loop I’m going to use let I’m going to say let I equals zero and then we’ll say as long as I is let’s say less than or equal to 10 and then we’re going to increment by 1 and then here I’m just going to do a console log of I so if I save that what it’s going to do is just start at 0 and it’s going to Loop through and console log each number until it gets to 10. so for very simple for Loop now if I were to come outside of this and do console log I you’ll see I’m going to get an reference error I is not defined so I is is scoped in this Loop in this block now I want to show you the difference between VAR versus Latin cons so I’m going to create a block here just an if statement and just say true and let’s create a cons variable of a so we’ll set that to let’s say 500 let’s say let B we’ll set that to 600 and then let’s use VAR C and set that to 700. okay now if I come outside of that block and I console log a we’re going to get an error by console log B we get an error and if I console log C it works you’ll see 700 so that’s the big difference between VAR versus let and const VAR is not block scoped so if you have a variable that you created with VAR inside of an if statement that can that’s accessible from outside and that’s not really good that’s not what you want you want your variables to be block scoped that’s how most programming languages work so in es2015 or es6 they decided to create let and const but of course you can still use VAR because if they they took VAR out that would break a lot of projects so yeah I would always say use Latin const now even with loops if if I used VAR here instead and then I come down and uncomment this console log I you’ll see that it’s actually giving me 11. so it’s not throwing any type of error it’s working and giving me 11 which obviously I don’t want that to happen now VAR is function scoped so I want to make sure that I explain that so if we come down here and I create a function called run and then in here I say VAR let’s say I don’t know D and set that to a hundred right so obviously I can use that here I’ll say console log d and of course I have to run the Run function and now at the bottom you’ll see a hundred and then if I try to come outside of here and console log d I’m going to get an error even though I use VAR because VAR is function scoped okay if you can’t access a VAR variable that’s inside of a function outside of a function but you can with other blocks like loops and and if statements now there’s one other thing that I want to mention about VAR so let’s say we have let’s say const Foo equals one and then let’s say VAR equals two so when we set a global variable with VAR let me just comment that out get rid of that error when we create a global variable with VAR if we look at the window object let’s take a look here you’ll see that it actually gets added to the window object when we use letter cons that does not get added to the window object so you can see here there’s no Foo so that’s another kind of difference between constant Latin VAR and you’re probably not going to want your Global variables on the window object all right guys so now we’re going to look at how scope works with nested functions and nested blocks now nested functions relate to something called closures and we’ll look at ways to use closures later on but I think it’s a bit too early to to learn them a lot of people are intimidated by them but we can at least look at how Scopes work with nested functions so let’s go ahead and create a function I’m going to call it first and then in first we’ll create a variable called X set it to 100 and then what I can do here is Nest another function so I’m going to call this one second okay so it’s nested inside first and here we’ll create a variable called Y and set that to 200 and then in second I’m going to console log X plus y now in order for a second to run I have to call it within first right so we’re going to run second here and in order for first to run I have to call it here so I’m going to go ahead and save that and you’ll see I get 300. so you can see I can access from the parent function from I should say from the child I can access any variables that are in the parent scope however it doesn’t work the other way around I can’t access from the parent variables in a child scope so if I if in first I try in console log y then that’s going to give me an error okay so remember you can access parent variables but you can’t access child variables so they’re two separate Scopes now it’s very similar with blocks so let’s go down here let’s say if we’ll just say if true and then in here I’m going to say const x and I’m on a different scope so I can use x and then let’s say we have another if a nested if and here we’ll say if x equals 100 and again I know we haven’t gone over if statements we’re going to get to that soon I just want to show you this this is kind of the same type of thing where we have let’s say Y and we can console log here um let’s say X Plus y and if I save that we have to comment this out because it’s giving us an error if I comment that out you’ll see we get 300 right because I’m able to access here I’m able to access the parent Scopes variable of X but if I go outside of this this child if or this nested if and I try to console log Y which is created in there then that’s not going to work okay because this is a separate scope that I can’t I can’t access but you can access the parent from within the child so hopefully that makes sense I know it’s a little confusing but I figured this was a good place to mention this since we’re talking about scope okay so up to this point we know how to declare functions and invoke them or call them or execute them however you want to put it there is another way that we can create functions and that’s with a function expression so let’s first declare a function just like we’ve been doing so I’ll say function this is called a function declaration right so we do that by just putting the function keyword first and then let’s call this add dollar sign and what this will do is take in a value and then just prefix it with a dollar sign so we’ll return from this a string with a dollar sign and then we’ll just concatenate the value and then if we want to invoke it we can just well let’s let’s do it in a console log since this is returning so we’ll say add dollar sign and let’s pass in here 100. so if I save that we get 100 so that’s a function declaration we start off with the word function and then name it and so on but we can also use a function expression where we actually create a variable so let’s call this add plus sign same idea of it with a plus sign and we set that equal to a function and that will take in a value and then we’ll go ahead and just return we’ll do a plus sign and then we’ll concatenate the value and then if we want to invoke it we can do a console log and say add plus sign and let’s do 200 and if I save that we get plus 200. so notice that we invoke them the same exact way we just call the function pass in a value but they’re declared differently the the expression is just a variable it’s a function assigned to a variable now in JavaScript you don’t have to use semicolons they’re optional but notice at the end of the expression we do have a semicolon we don’t add a semicolon to the end of a function declaration now there are some differences here and it comes down to something called hoisting now I’m not going to really go into hoisting as far as how it works right now I’ll do that later when we talk about something called the execution context but in very simple terms hoisting is the process of moving all the function and variable declarations to the top of the current scope before the code is run so you can think of it before your code is actually executed you can think of a step before that where it goes through and it looks for all your func function declarations and your expressions and your variables and puts it all at the put puts all those at the top of the page now even though this happens only function declarations are available before the code is executed so let me show you what I mean if I take this right here where I’m calling add dollar sign and I move it up above which whoops where it’s actually declared and I save that it works which might seem a little weird because we’re calling add dollar sign before we actually defined it so how does it know that and the reason for that is hoisting because again there’s you can think of it as a separate step before your code is actually executed where this is moved up top now like I said only declarations are available before the code is executed so if I do the same with an expression if I take this console log and I move it above where we where uh where we Define it and I save that it says uncut reference error I cannot access add plus sign before initialization okay so when you use a regular function declaration you can call it beforehand if you wanted to put all your functions at the bottom of your script you could do that although I really wouldn’t recommend it I think it’s much cleaner to have your functions declared or defined and then use them but uh but yeah I just wanted to go over declaration versus expression in the next video we’re going to look at another type of function expression and that’s Arrow functions so Arrow functions were introduced into JavaScript in 2015 they were part of the es2015 or es6 update and they there’s some advantages to using Arrow functions of course they’re more compact they also have an implicit return which I’ll show you and they also have a lexical scope which I’ll talk about a little later so let’s start off here by just creating a regular function declaration like we’ve been doing so just a simple add function that will return a plus b and then we’ll call that we’ll just do a console log of ADD and pass in one two so we get three now let’s let’s rewrite this as an arrow function so I’m going to go right underneath it and we’re going to say const add and remember in the last video I showed you we can also create function Expressions so I could do equals function like this now an arrow function we can actually get rid of the function keyword and then instead of using the function keyword after the parentheses we’re going to use an arrow or what we call a fat arrow and then we can pass in any parameters and then in the print curly braces here we can just same thing just return a plus b if I save that we get 3. so this is the just the regular Arrow function syntax now there are some things we can do to make this even shorter since we only have a single expression single just one line expression here that we’re returning something we can shorten this by getting rid of the return statement and the curly braces so instead of using add though I’m going to do subtract just so I don’t have to comment that 102 but we’ll say can’t subtract and it takes in A and B we have our Arrow now instead of putting my parentheses here I’m just going to directly say a minus B so this is saying I want to return this expression to the right of the arrow so this is the same as this of course except it’s it’s subtracting so I’ll go ahead and copy this down and let’s do we’ll say 10 5 and we’re going to call subtract and of course we get 5. so this is in PL it’s an implicit return because we’re not specifying the return keyword it’s just doing it so let’s say implicit return now there’s another way that we can shorten things up if your function only has a single parameter so let’s say we have a function called double and it takes in a single parameter and then what we want to return is whatever we pass in and then just multiply it by two so let me just run that down here real quick so if we do double him pass in 10 we get 20. now the way we can make this shorter just a little shorter but it’s important to know this is when we have a single parameter like this we don’t need to have parentheses around it okay now the way that I have my text editor set up and prettier and auto format if I save it puts it in automatically but what I can do is copy this I’m going to copy it and then comment it out and then over here in my console I’ll paste it in and you’ll see that that works so if I do double let’s say double um one we get two now if I try to Define this and leave off my parentheses but I have more than one param that’s not going to work okay so you can only emit the uh the parentheses when you have a single param so let’s uncomment these and just put a comment here and you can say can leave off parentheses with a single param now another thing that can cause a little bit of confusing of confusion is if you are returning an object so let’s say returning an object and this is due to the formatting of the you know having the arrow point to curly braces when you want to return an object with which also use Curl uses curly braces so to give you an example let’s say const we’ll call this function just create object and it doesn’t have to take anything in but let’s say I want this to return an object that has a name I’ll just do that and then if I save you’ll see that prettier automatically thinks to put a semicolon here which obviously isn’t what I want if I’m trying to make this an object so if I come down here and I do a console log of create object I’m going to get undefined so all you need to do is if you want to return an object this way you just surround the curly braces with parentheses and then of course we don’t want that semicolon so now if I save you can see we’re returning an object that has the name of Brad now I know we haven’t gone over high order array methods or callbacks or anything but that’s another great place to use Arrow functions so I’m just going to show you an example so let’s say we have an array which we’ll just call it numbers and let’s do one through five and on arrays there’s a method called for each and we haven’t gone over this yet but we’ll be getting deep into these types of methods later on but just to show you if we do numbers dot for each what you pass in here is a function okay and you could do it like this you could just pass in a regular Anonymous function and just pass in whatever you want to use for each number I’ll just use a variable called n and then I’ll just do a console log of n if I save that you’ll see it basically what this does is it Loops through and it just outputs logs each number okay I could do whatever I want with this number but I’m just choosing to log it out now this is a good place to use an arrow function because you can really shorten it up and make it neater so let’s say four each and instead of passing in the word function I can just put in my parentheses pass in actually in this case I wouldn’t even need parentheses since I’m using a single a single parameter but it’ll add it automatically in my case and then we have an arrow and since I just want to do a single console log I don’t even have to use curly braces I can just say I want to do a console log and Save like I said the parentheses get added but you really don’t need them and you can see it does the same thing so I think that this is you know more neater and short and concise than this but again it’s it’s all preference just like most things so this is let’s say Arrow function in a callback so callback is basically when we pass the function into another function and we’ll we’ll get into that later all right so hopefully this just gives you a basic understanding of how to format Arrow functions we’ll be using them throughout the course now in the next video I want to get into something called immediately invoked functions all right so when we deal with functions we usually Define them or declare them and then we invoke them when we need to run them however there is a way in JavaScript that lets us create a function or declare a function and invoke it at the same time and that’s using something called an immediately invoked function expression or an iffy for short iifi I’m sorry iife and there’s a few reasons why you might may want to do that one of the biggest is to avoid Global scope pollution so let me show you what I mean if we have in our folder here you can see I have a folder called iffy if I create another Javascript file I’m just going to call it other script dot JS and this could be like another library that we’re using or whatever it might be and let’s say in this script we have a global variable called user and I set that to Brad and I’ll just do a console log of the user and of course it’s not going to show yet because I haven’t linked it up to my HTML file so let’s go ahead and add that and we can say that this is coming from some other library that we didn’t even write so that another developer created so we’ll say another script.js if I include that now we’re seeing that that Brad value which is in this user variable now let’s say in our script well we want to have a variable called user as well so I’m going to set const user to John and as soon as I do that and save and it runs I’m going to get this user has already been declared okay because it was declared in the global scope of the other file and now I’m trying to declare it in this scope as well and there’s a few ways to handle this but one of the ways we could handle this is with an iffy so let’s go underneath here and I’m going to open up a set of parentheses the Syntax for an iffy is a little strange what we do is create an unnamed function in those parentheses and then whatever we want to happen so I’m going to actually bring bring this down into the iffy and then just do a console log of user now after the the first set of parentheses we need to open up another set to invoke it right because that’s a function we need this set of parentheses to invoke that so I’m going to go ahead and save this and you’ll see now we get we don’t get an error we’re able to have both of these variables of user because this this one here is not in the global scope okay it’s in the scope of the iffy and I could even create a function within here like let’s say we have a function called hello we’ll use Arrow function and we’ll just do let’s say console.log and we’ll say hello from the iffy now if I try to go outside here and execute hello I’m going to get an error that says hello is not defined because again it’s it’s scoped inside of this iffy so I would have to run it inside here like that now you can add parameters if you want so let’s say I’ll just create another one down here so it’s remember it’s 2 it’s parentheses side by side the first one has the function inside of it so I could pass in let’s say name and then let’s say I want to just do a console log of a string hello and then I want to concatenate onto that the name now where I pass that in is going to be right here so I’m going to pass in a string of let’s say Sean save that and we get hello Sean so that’s adding parameters to your to your iffy now you can have a named iffy because notice these are just Anonymous functions they don’t have any any name associated so if I wanted to I could say function and then give it a name like hello which I can do because the other hello is on a different scope and then whatever console log hello but you don’t really see this very much because you can’t call that function outside of of the iffy outside of that scope you can call it within it and that’s something called a recursion when you when you call a function from itself that’s recursion and it’s kind of an advanced topic which we’ll get into later much later and I wouldn’t recommend doing it if you run this you’re going to crash your browser because what’s going to happen is it’s going to run hello it’s going to console log hello then it’s going to call it again it’s going to console log again call it again and it’s just going to keep going until your browser crashes is going to cause what’s called what we call an infinite Loop so I wouldn’t recommend doing that but I wanted to show you you can create a named function I guess the other reason you might do it is for debugging reasons all right so that’s it for iffys we’ll we’ll probably get into these a little later in some projects but in the next video I want to give you a couple fairly easy function challenges all right guys so we have a couple challenges to do so there’s three of them here and basically I’ll just do one by one and you can pause the video after I explain each one and try it on your own so challenge one is to create a function called get Celsius that takes a temperature in fahrenheit as an argument and then Returns the temperature in Celsius for bonus points write it as a one line Arrow function so we’ll write it as a regular function first and then we’ll see if we can convert it and the expected result you just pass in a Fahrenheit like 32 and you get back the Celsius which would be zero and you can make the output look prettier by putting it into a string you can even add the the slash X B zero which is this this little degree symbol and you know put it in a template string like that and then hence the formula for Fahrenheit to Celsius is this right here so basically this Fahrenheit minus 32 times 5 divided by 9. you can read more about the formula here if you want so that kind of explains that all right and then what I’ll do is open up let’s search for a Fahrenheit I don’t even know how to spell Fahrenheit Fahrenheit to Celsius converter online okay so here we have an invert and this just shows you the formula right here so basically we just need to um I’ll put this in our JavaScript where the Fahrenheit temperature is the argument so if you want to pause the video and do that now go right ahead so I’m gonna just put in a comment here say challenge one and let’s create it as a regular function first so we’ll say get Celsius and then that’s going to take in a Fahrenheit temperature and then basically what we’re going to do let’s just do Celsius and let’s set that to the formula which we can probably yeah we’ll just grab it right from here definitely need to know that stuff like this I usually find on like stack Overflow or using the the GitHub copilot extension is really helpful because it’ll get you stuff like that so I’m just going to paste that in and then what we can do is replace that capital F with our lowercase f because that’s the argument that’s being passed in right and then let’s return Celsius cell CS right and then let’s do a console log here of get Celsius and let’s pass in 32. so if we look at down here we get zero so let’s try something else if we pass in 40 we get four point and then a bunch of fours so if I put in 40 here we get same thing we put in 50 we get 10 let’s put 50 in our function and we get 10. good now we can turn this into a one line Arrow function if you want to pause the video and do that you can go ahead but I’m going to just I’ll comment it out in a second but let’s do const get Celsius we’re going to set it to an arrow function that takes in Fahrenheit and then we know that basically we just want to return this right here right we didn’t have to put this in a variable name we could return it directly but down here we can use an implicit return so I’m just going to paste that in all right and then we’ll go ahead and comment this one out and let’s try it again I save we get 10 if I pass in 32 we get 0. all right so this is a nice clean function so I think that that’ll do it and we could put it inside of uh a template string with this little symbol so for example instead of just logging the answer we could say we could put in back ticks and say the temp for what do we do here yeah we’ll just say we’ll just say the temp attempt is and then put in our get Celsius with 32 and then outside of that the curly braces I can paste that in and then we’ll put an uppercase C actually let’s not have a space there so now it says the temp is zero degrees celsius if I pass in 50 and say we get the temp is 10 degrees Celsius so that’s the first challenge so the next one I I don’t even really remember what these are I did these quite a while ago so create an arrow function called min max that takes in an array of numbers and returns an object with the minimum and the maximum numbers in the array so we want to be able to pass in an array of numbers and then what we get back in return is a an object with the minimum and the maximum of you know of the numbers in that array so as far as hints you can use the math dot Min and math.max methods to get the Min and Max you can also use the spread operator to spread the values of an array into separate arguments okay so yeah let’s try that and if you want to pause the video and do it that’s fine as well um I’m just gonna put a comment in here challenge two and let’s create our function called min max and then that’s going to take in in Array so I’ll just call this ARR and then remember we can use the math object Min and Max methods so let’s say const min and we’ll set that to math.min and then I want to take basically this this doesn’t take in an array it takes in just a bunch of numbers like this one two three and so on so if we want to take just the values in the array remember we can use the spread operator and then we’ll go ahead and add our array and just to kind of test that out let’s do a console log of uh Min and then we should we can just call this because we we logged from the function erased oh we didn’t we need to pass in an array so let’s just do one through five and save and we get one which is the the minimum so now we can copy this down and let’s get the max So Max and then I’m just going to console log Max and we get five if I add to this 6 then I get 6. so we know we’re we’re halfway there we have that now we just need to create an object so let’s go down here and let’s return an object with Min now remember when if if your variable name is the same as your your key here you don’t need to have the variable name you can just do that and then same with Max all right so that should do it now we’re returning so we do need to wrap this in a console log if we want to print it out and we’ll save so we get min 1 Max 6. if I add let’s say 31 in here and I save we get min 1 Max 31 if I get rid of the one Min will now be 2 max 31. okay so that should pass the challenge now for our Challenge three it says create an iffy we talked about those in the last last video that takes in the length and width of a rectangle outputs it to the console in a message as soon as the page loads so we know that if we write it in iffy it runs right away when the page loads so on page load we should see this message an area of a rectangle with a length of 10 and a width of 5 is 50. okay so the hints the area of a rectangle is the length times the width okay so it takes in the length and the width that means we just need to multiply it and this should get passed into the ifeas arguments you do not have to return anything from this function just log to the console so that’s actually pretty easy um so it really just tests your skills to create an Effie so let’s come down here and you can pause the video right now if you want to so let’s say challenge three and we’re gonna create an iffy so remember we have a set of parentheses and in that is where we create our function now I don’t think I showed you in the last video that we can actually use an arrow function here like I could do just a regular function like this but you can also just do this so that’s what I’m going to do and it said to take in a length length and width and then inside the function body let’s get the area so we’ll say const area and then we can get that with length multiplied by the width and then let’s just do a variable for the output we want to log so that’ll be a template literal and we’re going to say the area let me just check this out again I’m actually going to just copy this so if we paste that in and we just need to replace these values so we know we have the length and the width passed in so we can replace this 10 right here with the length we can replace this 5 with the width and we can replace 50 with the area and then of course we need to add in our parentheses and then when we pass in the the arguments that goes in here so let’s say 10 and 5. and of course we need to Output this so let’s just do a console log and well we’re going to Output output so the area of a rectangle with a length of 10 and a width of 5 is 50. so if I were to change this now let’s say 20 and 10 save that length of 20 and a width of 10 is 200. all right guys so I hope that the the challenges I hope the description is good enough for you to kind of understand what I’m asking you to do I’m not the best at at doing challenges or creating them honestly so hopefully that’s sufficient all right so what I want to start to talk about next is the execution context which is more behind the scenes stuff and and how how things work behind the scenes which is a little Advanced especially for this stage in the course but I said it a million times already I want to give you a full picture of what’s what’s going on as we’re writing our code all right guys so now we’re going to talk about execution contacts which might sound a little intimidating especially if you’re a true beginner but just know that learning this stuff now and learning the the bigger picture of what’s happening when your code is running is going to benefit you more than if you learn this stuff two three years down the road like I did so execution context just think of this as something that’s going to happen behind the scenes we’re not looking at any new Advanced code or anything like that in fact the example code we’re going to use is just very simple stuff we’ve already done just creating a variable creating function running a function all right now as far as what this is the execution context is a special environment that’s created by the JavaScript engine in the browser or if you’re using node.js the the engine that node.js uses which is the V8 engine and this special environment this execution context includes the currently running code and everything that aids in its exit execution and when it’s first created that’s called the the global execution context okay you can think of it as like the global scope and then anytime you invoke a function that function will have its own execution context that’ll last for the span of the function okay when the function is done then that function execution context is done now to kind of visualize the execution context I created this box so you can think of it as a box with two sides where you have your variable What’s called the variable environment on one side and this is going to be all the variables and all the functions in your code stored in key value pairs in memory all right so that’s the memory and then we have the execution side which is the thread of execution so JavaScript is what we call a single threaded language a thread you can think of as like a process and your code is executed line by line on that thread or on that process all right so just to be clear JavaScript is single threaded and it’s synchronous so it’s executed line by line there are asynchronous capabilities which we’ll talk about later different web apis and stuff like that but just know that at its core JavaScript is single threaded and it is synchronous now there’s two phases when the execution context is created so the first phase the memory creation phase you can think of as like one swoop through before your code is actually run okay so the memory creation phase does not actually execute your code it does a couple things so the first thing it does is it creates the global object in the whether that’s in the browser or in node.js in the browser the global object is called window in fact if I go to Chrome real quick and I go into the console and I type in window and I hit enter it’s going to show me that window object and all the methods and properties on it and there’s a ton of them okay different apis and stuff and we’re going to get into a lot of this later on now and that’s created by the execution context in the memory phase now the second thing it does is it creates the this object and binds it to the global object that’s why if I come in the console and I type in this and I hit enter it’s going to show me the same exact thing the window object because that’s it binds it to that all right then what it does is it sets up the memory Heap for storing your variables and function references so remember this box right here all your variables and functions are going to get put into here during the memory creation phase and then the last thing it’s going to do is it’s going to set the value to all of those to undefined okay so if we look here these these values here these are all going to get set to undefined in the memory creation phase they don’t get filled with values until the code is actually executed okay which is the second phase the execution phase where it goes through line by line and if it hits a function a function invocation then it will create a new execution context for that function now to give you a better picture we’re going to go through we’re going to step through each line of this code and I’m going to show you exactly what’s happening within the execution context and like I said this code is very simple we’re just creating a couple variables we’re creating a function that returns a sum of two numbers and then we’re just creating some variables that will contain the return value of this get sum function so a couple things to keep in mind there’s two phases we’re going to go through the memory creation phase and the execution phase and whenever we invoke a function like this it creates a kind of a side function execution context so let’s get started so we go ahead and run them the memory creation phase or we don’t run and it just gets run and on line one it’s going to set the x variable in memory it’s going to allocate it and store it as undefined okay remember I said variables in the memory creation phase are they’re put into memory but they’re stored as undefined it’s going to do the same online 2 with the Y variable store that to undefine now line three it hits a function and functions are allocated to memory but they’re not stored as undefined I think I might have said that the the all the code within the function gets stored to memory okay it doesn’t get executed it just gets put in memory for now and then it’s going to skip to line seven where someone is going to get allocated to memory stored as undefined okay we’re not remember we’re not executing anything yet so the functions don’t get executed we’re simply putting the the variables into memory same thing with sum2 that’s put into memory stored as undefined now what’s going to happen is it’s going to go through the execution phase so it’s going to go back to line one and in line one it’s going to take 100 and put that into the X variable in memory remember X is already in memory as undefined from the creation phase but now that we’re executing it’s going to put 100 in for X okay next line 2 is going to place the value of 50 into the Y variable then it’s going to go to line three but it’s going to skip this function because there’s nothing to execute this is just a function a function definition then we go to line seven it’s going to now invoke get some because remember we’re in the execution phase so this is a function it’s going to get run and it’s going to create a new function execution context all right now remember when we when a new execution context is created it has two phases once again so now we’re going to be in the memory creation phase 4 the get sum function execution contacts so you can think of it as like a nested execution context so on line three what it’s going to do in the memory creation phase is it’s going to assign N1 and N2 to memory and store it as undefined okay remember we’re in the creation phase for the function execution context so it’s going to take these two and store them in memory as undefined then it’s going to go to line four it’s going to store sum as undefined it’s going to go to the execution phase now of the function so N1 and N2 are going to get a signed 150 and the reason for that is because we’re passing in here X and Y which are set to 150. okay and then on line four the calculation is done and 150 is put into this sum variable in memory then line five is going to return and tells the function execution context to return to the global execution context with the sum or the value of 150 okay and that’s going to get stored in here the return sum value is put into the sum 1 variable then it goes on to line eight it’s going to do the whole thing over again it’s going to open up another execution context for the function and do the same thing just with different parameters this time 10 and 5. all right so just to quickly recap because I really want you guys to get this we run this block of code it starts the the global execution context in the memory creation phase it goes through each line and it’s going to set all the variables to undefined in memory it’s going to set the function code into memory okay once it does that it starts the execution phase where 100 is put into x 50 into y it’s going to skip the function declaration because we’re in the execution context there’s nothing to execute once we 7 it sees there’s a function that opens up another execution context for the function okay and then it goes through the memory phase for the function then the execution phase for the function and then moves to line eight and it’ll have to do the same thing because we hit another function all right so this doesn’t really affect how you write your code right now but it will benefit you in the future just knowing how this works behind the scenes now in the next video I’m going to run this block of code and I’m going to use the the browser debugger to kind of put breaks in so we can see exactly what’s happening or as much as we can see within the browser so in the last video we talked about execution context and we stepped through a block of code and I showed you what happened during the memory creation phase and the execution phase well here I’m going to do the same thing you can see I have the same exact code in in my vs code and we’re going to do the same thing from within the browser and we can do that by using the sources tab in the dev tools and over here you’ll see our files and if I click on script.js we’re going to see this the same code right here now using the debugger I can put what we call a break point anywhere I want and that’s going to stop the code from running at that point so what I’m going to do is put it right at the beginning so it’s actually not going to execute the script so I’m going to reload the page and none of this is executed but the memory creation phase has been run so down here you can see all these variables X Y sum 1 some to there they’ve all been put into memory and set to undefined because remember with with the memory creation phase it puts your variables in memory and sets them to undefined okay before the execution now remember functions get stored in memory and the entire code in the function gets stored however that’s going to be down here in global so that’s called get sum so if we look down here we should see a get some function right here all right so that code is stored in memory as well now one interesting thing is if you used VAR instead of const or let then those variables would be put on the the global scope as well and and that we can get into hoisting and stuff later on but what I want to show you now is if I step through this so I can use this little arrow icon to to execute the line the code line by line and you’re going to see what happens over here so I’m going to click the arrow it’s going to run the first line const x equals 100 and now we’ve started the execution phase okay normally it just goes through and does it you know all together but uh or it does it real fast it doesn’t pause like this but now we’re pausing line by line and you can see that 100 has been put into X okay because we’ve started at the execution now I’m going to click this Arrow again and execute the second line and you’ll see that 50 has been put into y now it skips the function definition because there’s nothing to execute and goes right to this get sum where it where it’s being invoked now remember when we invoke a function it creates a new function execution context I’m going to click the arrow and now you’ll see this new area called local which is our function execution context and the first line has been has has Ran So N1 and N2 contain 150 because our first function call we passed in X and Y which are 150. now if I click this again and run this line right here it’s going to put 150 into sum so I’ll click it again and now you’ll see sum has 150 in it now if we step out of the function it’s going to go to the next get sum which is being passed in 10 and 5. so it’s going to open up a new execution context with 10 and 5 as the arguments here is the variables if I clicking again it’s going to add the sum click it again it’s going to go to the next line to the console log and now our script has been run all right so that’s what it looks like when you go through line by line but you saw even before we executed anything the creation phase ran and put our variables and our function into memory but if this is confusing to you don’t worry about it my my point of doing this is just to show you what’s going on under the hood and how this is actually run within the browser so in the next video we’re going to talk a little bit about something called the call stack and then after that we’ll get back to syntax creating conditionals and loops and so on okay so while we’re on topics that are kind of behind the scenes things that happen when we run our code we talked about the execution context I want to also talk about the call stack this is something that will be important later on when you get into more advanced JavaScript but I just want you to understand the basics of it so when we run a function we know that it opens up a new function execution context it also gets added to something called the call stack now a stack is a data structure in not just JavaScript but in in many programming languages and it operates in a very specific way it’s it’s last in first out or l-i-f-o meaning that the last thing to come on is the first thing to come off and the better the next slide will give you a better visualization of that but the call stack is you can think of it as a manager for your functions or a manager for your your execution contacts and at the bottom of the stack you have your Global execution contacts and then when a function is invoked that gets put on the call stack when it’s done it gets it gets popped off all right so if we look at this very basic piece of code here we’re running three functions or creating three functions for our second third and then running them okay and we’re doing this all in the global scope they’re all being run in the global scope so what happens here is the first function is invoked it gets pushed onto the the stack that’s the terminology just like with arrays push and pop so it gets pushed on first ends and then gets popped off then second runs gets pushed on popped off then third runs gets pushed on popped off so that’s how this piece of code would work with the call stack now this piece of code is a little different so we again we have first second third but we’re just running first in the in the global scope and then in first we’re running second and then in second we’re running third so what happens is we run first it gets pushed on while first is running second is run so that gets put put on top of first because first is still running it’s still open and then in second third gets called so second is still running so third gets pushed on when third ends third gets pushed off I’m sorry popped off and then second end gets popped off first popped off so it’s just it’s the same thing it’s last and first out so what I want to do now is show you that those same two pieces of code in the browser and show you the call stack in the sources tab so as you can see I have the first example I showed you here I have the second one commented out for now and I’m going to go to the sources tab and go to script.js and what I’m going to do is put my my break point right at the first function where it’s called and then I’m going to reload the page and right now it hasn’t run anything I’m going to once I click this Arrow it’ll run this line the first function and if you look down here there’s actually a tab called call stack and you can see right now first is on top of is is is first on top of the global execution context that’s what this Anonymous is all right so first gets put on the stack and then let’s step through it step through it again finish it up now we’re going to run second gets put pushed on the stack step through it it gets popped off let’s run third that gets pushed on WE step through it and then it gets popped off all right so that’s how this piece of code works just like I showed you in the slide now I’m going to just comment this out and the second example I’m going to uncomment that so remember this is where we’re actually running second in first and third and second so I just want to show you how this would work so we’ll come down here actually let’s uh let’s just reload this whole thing real quick and then I’m going to put my break point right here at first and then reload and then if we run the function you’ll see that first is put on the stack now it’s going to go to Second which is still in first okay and we’ll run that and now look second is on top of first inside second we run third so let’s do that and now third is on top of second so this looks exactly like the diagram that I just showed you all right and then if we step through third will end gets popped off now you can see second is on top we’ll run that that gets popped off first that gets popped off so I just wanted you to understand at the very at a very basic level how the call stack works so in the next section we’re going to start to look at control flow and logic and conditionals hey guys welcome to section four so I know that some of you might be getting a little antsy because you want to get into the the document object model stuff and creating things in the browser and events and all that and that’s coming soon I promise but this stuff is very very important these are the fundamentals these are things that you absolutely have to know to do anything in JavaScript so in this section we’re going to look at logic and control flow which is something that is very important not just in JavaScript but in any programming language because you need the ability to make decisions you need the ability to run certain blocks of code if something is is true or false so we’ll be looking of course at if statements or if else statements we’ll be looking at switches I want to get more into the truthy and falsy values I know we touched on that a few sections back but I really want to dive into that logical operators logical assignments shorthand if statements and the ternary operator so that’s the the type of of stuff I want to get to here we’re going to have a couple challenges as well alright so let’s get into it all right so one of the main ways to have control of the flow of your application is with if statements and if statements are in just about every programming language if they’re not then there’s there’s most likely something similar so the format of an if statement is very simple we just say if and then in here we can put either a value or an expression so I’m just going to put true in this one and then if that passes so if it’s true then whatever I put in here will run I’m just going to say this is true if I save that you’ll see that that runs now if I were to copy this down and change this to say false and then we’ll say this is not true if I save that that’s not this block of code right here line six is not going to run because this expression that I passed in is false all right now we can also evaluate expressions that with uh with operators like equals or less than so I actually have a chart right here so we can test if something is equal to with both double and triple equal signs or not equal to greater than less than and also greater than an e or equal to or less than or equal to so just to give you a quick example and let’s actually create a couple variables here we’ll say x equals 10 and let’s do y equals 5 and we’ll say if x is greater than y then let’s just do a console log put through some backticks in here and we could say x is greater than y save that and we get 10 is greater than 5. if I want to use an equal sign or our triple equals whatever not quadruple equals that’s not a thing and then here we’ll say x is equal to Y if I save that this block of code isn’t going to run because this is false right if I change y to 10 and I save then that will run now this one’s not going to run because 10 is not greater than 10. if I were to use greater than or equals that will run okay so we could say is greater than or equal to save that we get 10 is greater than or equal to 10. now as far as if else goes if I change y back to 5 this right here this block of code is not going to run but we might want something to happen if this is false so if this is true this line will run then we can add an else if we want and say let me just just copy this and I’ll say is not equal 2y so if I save that now we’re going to get 10 is not equal to 5. so the else is going to run because this expression is false now we talked a little bit about we talked quite a bit about scope in in the last section but I just wanted to remind you that blocks like if statements have their own scope so if I put it doesn’t really matter what I put in here I’ll just say if X is not equal to y and then I just want to show you in here if I were to create a variable like let’s do Z and set that to 20 and let’s say console log and let’s see X I’ll just say I don’t know we’ll just say Z is 20. it doesn’t really matter what I want to show you here if I save that we get 20 is 20. but if I were to try to access that Z variable I can’t do that Z is not defined and that’s because I use const if I use let here to Define Z I get the same thing if I use VAR it actually works because VAR is not Block Level scoped it’s function scoped like it you can’t use if I were to say VAR Z in a function I can’t use it outside of that in the global scope but with other blocks like loops and if statements it’s not scoped okay so and that’s it’s not a good thing that this is not scoped because then someone might want to access that Z variable somewhere else and they’ll be able to so that’s why Latin cons to are actually created was to keep Block Level scoping now the next thing I want to show you is some shorthands that we could use I don’t really do this and and recommend it but it is possible so let’s take this right here this if statement and let’s just say shorthand if so paste that in and I’m not talking about the ternary operator we’ll get to that later but I can actually get rid of the curly braces here so that is perfectly valid JavaScript if I save that we get 10 is greater than or equal to 5. all right and then if I wanted to use an else I could after the semicolon do else and without parentheses I’m sorry without curly braces we’ll say I don’t know it doesn’t matter we’ll say this is false and save that and if I change let’s say y to 50 and save that you can see this is false now this this looks cluttered to me I don’t like it I I would use parentheses but everyone has their own preference but I just want to show you that if you have multiple lines like right here we just had a console log if this was true you can do this with multiple Lines by using a comma so let’s say I also want to log let’s say console.log this this is true and if I save that you’ll see I’m not getting any errors if I change this back y back to 5 and I save it’s going to run both this line right here and this line right here this is this it’s true this is true so you can do this but I really don’t like the syntax and wouldn’t suggest it all right so that’s it for just the basics of of um if statements in the next video I want to get into else if as well as nesting okay in the last video we looked at if statements and if else where we said if something is true do something else do something else now you might have situations where you have multiple conditions that you want to test and do and run some block of code based on these multiple conditions and that’s where else if comes in so let’s make this a little bit more interesting we’ll create a date so we’ve already looked at the date object and I’m going to set it to a specific date let’s do 10 uh we’ll do 10 30 22 and then I want to put the time so eight we’ll do eight o’clock so eight zero and zero and remember you can pass a string in here if you want doesn’t have to be these um these arguments and then I want to get the hour because that’s what I want to test so I’ll say const hour and then on the date object we’ll run the get hours method and if we console log that so console log our then we’re going to get eight right because I set it to eight if you if you don’t pass anything in here it’s going to give you your current hour so mine would be 10. but we’re going to keep it at eight so we’re all on the same page and then let’s do an if statement here so we’re going to say if the hour is less than 12. all right so if the hour is less than 12 then let’s do a console log of good morning all right because it’s less than 12. now I could do else here so if I do else we could do console log and let’s say good night and if I run this I’m going to see good morning because it’s 8 right now what if I want to say good afternoon if it’s at a certain time in that case I would do an else if so I’m going to go where this else is where this uh this first ending curly braces and just put that on the next line and then say else space f and then open up a set of curly braces and we could put this here and let’s say if the if the um what is it our is less than 18 then let’s say console log and we’ll say good afternoon all right so basically if it’s less than 6 p.m it says good afternoon now we’re getting good morning even though it is less than 18 right we’re at eight but this ran first so it’s going to first look at this if the hour is less than 12 which ours is then this is going to run and it’s not going to do anything further if the if the time is let’s say 13 and I save now we’re going to see good afternoon because this doesn’t pass the first one right so it’s going to say else if the hour is less than 18 which it is it’s 13 so now that’s going to run if I change that so that this is also false so if this is false and this is false if like if we say 19 then the else the final else is going to run okay so that is the else if now we can also nest if statements let’s say nested if so I’m going to say if let’s say our is less than 12 and actually you know what we’ll just let’s just copy this because I’m doing kind of the same thing here but I want to show you how we can Nest this to get even more options so let’s say if the hour is equal to six if it’s 6 a.m then we want to console log wake up so we know that in here it’s going to be this this code is going to run if the hour is less than 12. obviously 6 is less than 12. so what I’ll do is in here I’ll Nest another if statement and we’ll say if the hour is equal to 6. then let’s console log let’s say wake up okay so that’s how we can nest and maybe maybe at night time let’s go down here and let’s Nest another if statement okay and we’ll say if the hour if the hour is greater than or equal to 20 then we should be sleeping so say console log and we’ll just put uh a bunch of Z’s in here all right so let’s save that and we’re still going to see good night because we’re at 19 right now if I were to put the hour to six and save then we’re going to see wake up if I put the hour to uh and we’re going to see good morning if I put the hour to let’s say 21 we should be asleep so now we see good night and we see the Z’s so that’s nested if and you can Nest as many levels as you want you could go in here and put another if statement but that’s when you when you get to that level you might want to think about something like a switch which I’ll talk about in the next video now another thing we can do is have multiple conditions in a single if statement so for instance let’s say if the hour we’ll say if the hour is greater than or equal to 7 but let’s say I will also want to test if it’s less than 15. in that case I could put a double Ampersand and that’s going to be the and operator so I could say and if the hour is less than 15. so let’s say that’s the work day so I’ll just do console log and say it it is work time all right so if I save that I don’t see it because right now the hour is at 21 but let’s set it to we’ll say 9 A.M and we’re going to see it is work time now this is just one operator the and we could also do or so maybe we want to say if the hour is let’s say equal to 6 or which is going to be the double pipe characters or the hour is equal to 20. then let’s say that’s the time we brush our teeth so we’ll say brush your teeth save that now if we put the hour at either 6 or 20 so at 6 we’re going to see wake up and brush your teeth okay the wake up is coming from right here and the brush your teeth is coming from here because the hour is 6 or 20. okay so that’s or and then this one is if the hour is greater than or equal to 7 and the hour is less than 15. all right so in the next video I’m going to show you another way that we can evaluate expressions and do certain things depending on the result with something called a switch all right so now we’re going to get into switches which is another way to evaluate expressions and values so let’s go ahead and create a new date just like we did in the last video so I’ll say new date and let’s just do 2022 yeah we’ll just do uh arguments so 2022 one so that’s the month and then whatever 10 and we’ll do eight zero zero so it’s eight o’clock and then I’m gonna get the month so let’s say const month equals get month D I’m sorry D dot get month and then let’s check that out so month and save and we get one so we’re in January all right now I’m gonna create a switch that takes in month and evaluates it so basically we we look at month and we can create different cases for the value so for instance the case of it being one so this is the syntax case then the value and then a colon and then this is the block of code we would run so I’m just going to do console log and we’ll say it is January and then once we’re done in this case we want to write a break statement so we just say break which is kind of like a return it just breaks out of this case and then we’ll do case two colon and do a console log here and say it is February and break and we’ll do one more case three and console log and say it is oops it is March okay now if it doesn’t match any of these what you want to do is have a default so whatever you put in this default will happen if it doesn’t match any one of those so I’ll say it is not January February or March and we don’t need to put a break on the default so I’m going to save this and you see we get it is January now if I come up here and I change the month to two it says this is February if I change it to three it is March and if I change it to four or anything else it’s going to say it is not January February or March all right but I’m just going to put it back to January so I mean switches are most commonly used with immediate values meaning it’s we’re checking the month directly you can use it with ranges though like we did with the hours in the last video so for example we could do switch and then what we would do in here is pass in true and then we could say case and say our actually we didn’t Define our yet didn’t did we so let’s go up here and let’s just do what we did in the last video we’ll say hour equals D dot get hours and then we’ll come back down here and let’s say case hour is less than 12. and then we’ll console log here good morning and then break and then we’ll do another case and this one will be our is less than 18. and we’ll console log good afternoon and then break and finally we’ll do case hour actually we’ll just do the default and for the default we’ll do good night because obviously it’s not going to match anything else so if I save that we see good morning if I change the time because right now it’s the time is eight if I change it to uh let’s see 13 and save we’re going to get good afternoon and if I change it to anything above 18 like 19 it’s going to say good night so we can do it like this as far as ranges so those are switch statements you don’t see them they’re not as common as if statements but if you have something where you have like you know five six seven plus else if I think a switch is uh that’s a good use case for a switch all right you see them in like reducer functions and stuff like that when it comes to like front-end Frameworks and State Management and all that so those are switches in the next video we’re going to do a little challenge all right guys so now that you know how to deal with functions and conditionals we’re going to do a little challenge so let me just open this up here so the calculator challenge basically what I want you to do is create a function called calculator that takes in three parameters num1 num2 and then an operator and the operator can be plus minus multiplication or Division and the function should return the result of the calculation so if anything other than the four operators are passed in then the function should return an error message like invalid operator so as an example if we pass in 5 2 and plus we should get 7 5 2 minus three five two asterisk 10 and 5 2 2.5 and then if we pass in anything else that’s not one of these four operators you should get an error message you can return it or console log it or both as a hint you can use an if statement for the operator but this is also a good example for using a switch statement so it’s really up to you or you could do both so go ahead and pause the video try it out and then come back so what I’m going to do is use a switch so let’s create our function first it takes in num1 num1 num2 and operator and then I’m going to just create a variable called result and then we’ll run a switch on the operator and for the first case we’re going to look at see if a plus sign is passed in and this should have quotes around it because it’s a string if that’s the case literally then we’re going to set the results to num1 plus num2 and then we’re going to break all right and then what I’ll do is copy this down we want four of these because we have four operators to test so this one will be minus minus and then this one will be multiplication make sure that you change both here and here all right and then what I’ll do is for the default we’ll set the result because obviously it’s not going to be any of those operators so I’ll say invalid operator and then outside of the switch I’m going to first console log the result and I’m also going to just return the result all right and that should do it so now to test it out we’ll come down here and let’s do calculator and let’s pass in we’ll just use the example five two so we’ll say five two and then we’re going to pass in plus as a string we’ll save that we get seven if we do a minus sign we get three if we do an asterisk we get 10 and if we do a slash we get 2.5 and if I do anything else like an ampersand then we get invalid operator all right so that is the result that we’re looking for now if you used an if statement if you used elseif or whatever that’s absolutely fine as long as you get the same result so in this video we’re going to look at truthy and falsy values this is something for you to it’s really important for you to understand so try and remember these at least the falsy values because anything that is not falsy is going to be truthy and what I mean by that is if you have something you pass into an if statement that’s not something equal to or is something greater than maybe you had just have a string like an email so we’ll say test at test.com and then I pass that in here so I want to evaluate email and then I’ll just console log here you passed in in an email and if I save that you’ll see that that runs so this was evaluated to true or I should say coerce to true if you remember we talked about about type coercion where JavaScript implicitly changes the type so when you pass something into an if statement it’s always going to be coerced into a Boolean okay and we can even do a console log here and say Boolean and pass in email and you’ll see we get true the reason for this is that a string with anything in it is a truthy value okay so it’s always going to result to true so what I want to do is paste in that will do the falsy values first so let’s uh we can just just get rid of this and I’m going to paste these in so there’s six falsy values and what I’m going to do is set a variable let’s say const x and I’m going to set it to the first one which is false and I’m going to do two things I’m going to pass it into Boolean to see what it evaluates to and then I’m gonna I’m sorry that should be X and then I’m going to do an if statement so I’ll say if x and then we’ll say uh console log this is we’ll say this is truthy if this is true right and then let’s say else then we’ll console log this is falsy if I save that we’re going to get this is falsy and false because obviously false which is already a Boolean is going to be a Boolean false now zero if I pass in 0 to X we get the same result because if we pass zero into an if statement that’s a falsy value so we’re going to get false for that if we pass in an empty string that’s also a falsy value that’s why a lot of times like with web forms when you’re doing validation you’ll check to see if the value is there or not so in in it’s passed in as an empty string if it’s submitted as an empty web form or an empty input all right so an empty string null is also going to be falsy undefined is going to be falsy and then Nan are not a number is also going to be falsy now anything that is not falsy is going to be truthy so anything other than these six values right here but there are some things that are a little confusing that you might think are falsy and even even developers after like a year still forget that these are falsy some of these so I’m going to paste in some of these truthy values like I said everything else is not falsy but let’s try some of these so obviously true is going to be truthy right if we do zero but within a string of course that’s truthy anything in a string is truthy even a space if I put a space here that’s truthy but if it has nothing then that’s going to be falsy all right if I put false in a string that’s truthy because that’s not an actual Boolean it’s a string with something in it it doesn’t matter what it is as long as it’s something another thing that can be confusing is an empty array if I do that that’s truthy you might think if we say if and then an empty array you might think that that’s going to be falsy because there’s nothing in it but it’s still an array if you want to get the the length I’m sorry if you want to check to see if there’s something in an array then you want to check the length same thing goes with objects if we have just an empty object that’s also truthy if we have a function that has nothing in it that’s going to be truthy as well so this is really important for you to remember that it’s going to be true unless it’s one of these things right here now let’s talk about some caveats so I’m going to say truthy and falsi caveats I was going to do this in a separate video but we’re only at four minutes and something so let’s say let’s say we have a web form that’s asking how many children we have and I’ll create a variable to represent that so I’ll say Khan’s children equals two let’s say that’s what we passed in and then we want to validate the form so we’re saying if children then whoops then we’ll do something let’s just say a console log with backticks and we’ll say you have whatever number children and then else then we want to tell them to enter their children right the number of children so we’ll console log and say please enter number of children okay um and this is something you commonly see in web forms if a field is required so I’m going to save that we get you have two children right they passed in two pass in one you have one children now what do you think is going to happen if we have no children and we choose zero let’s say it’s a select field and we select zero well it says please enter number of children or I have no children so I’m selecting zero the reason it’s doing this is because zero is being evaluated here and zero is a falsy value so you can run into some issues with this I’ve actually seen this same issue over and over so a solution here one thing you could do is say is children not equal to undefined if I do that now it says you have zero children another thing I could do is run children through it uh not is Nan so is Nan is is not a number and what I’m saying here is is it not not a number if I save that that works as well you have zero children if I put in three that’s going to work as well so that’s another solution you could do um but yeah you just want to make sure you know what you whatever you’re passing in make sure you know what that coerces or what that evaluates to now another caveat that we see is checking for empty arrays so maybe you have an array of blog posts and if there are no posts you want to say like no post to show or something like that so let me just show you if we do const yeah we’ll just call this posts and we’ll set that to an array and we’ll say post one and post two right and then we’ll console uh sorry we want to do an if statement so if we say if posts then I’m just going to console log here list posts else then we’ll console log no pose if I save that it says list posts so I mean in real life you’d probably list your posts in the Dom which will you know we’re going to get to soon but if you have no posts and save it still says less post it doesn’t say no posts I will say no posts to list it doesn’t say that because an empty array is truthy right if we go up here an empty array is a truthy value so that’s going to evaluate to true so again know what you’re passing in so what you could do here remember we have a length property on arrays you can see that the length is zero if I add something in here then it’s one okay one two without whatever however many is in there so what you could do is say if post dot length is greater than zero now if I do that it says no post to list if I go in there and I add in post one and save now we get list posts so if you want to check for an empty array you want to do it like this now with objects let’s say check checking for empty objects so we’ll say const and I don’t know just say user equals and let’s set it to say name and Brad and then we want to check say if user then console log and we’ll just say list user else then we’ll console log no user all right so if I save that we’re going to get list user now if I if I empty the properties and it’s just an empty object It also says list user so you might want to check to see if there’s anything in the object and doing it like this is not going to work because this is a truthy value now we can’t use length directly on an object so if I if I were to try to console log user dot length you can see it gives me undefined so we can’t use length what you would do I mean there’s a few ways you could do this but one of the most common things to do is to use object dot keys and we looked at this in a past section if we say object dot keys and we pass in our user that will give us an array of the keys right so then since that’s an array then we can call length on it and we can say if that is greater than zero or you might want to say if it’s equal to zero then you would do this you know you might do it the opposite way around so let’s save that and now we get no user if there’s nothing in here if I add in a name and save now it says list user now another thing that can be confusing is using Lucy quality which is the double equal sign and this is one of the reasons that I I just about always use a triple equal sign so if we were to do a console log and say false double equals zero okay so we’re comparing false to zero and we’re getting true and the reason for that is because 0 is a falsy value and obviously so is false so if I were to do let’s say an empty string equals zero again I get true if I do no equal to undefined I get true so there’s many cases if you’re trying to compare these you’re not going to want true so that’s where the strict equality comes in if we add another equal sign to all of these oops then we’re going to get false for all of them because this will check the type as well okay um so again I always use triple equals but everyone has their own preference so those are some of the caveats that that you might run into when you’re dealing with true truthy and false values I don’t know if caveat’s the right word but some some areas of confusion so hopefully that clears that confusion up all right so in this video we’re going to get more familiar with the logical operators especially the double Ampersand and the double pipes which are the and and or logical operators so first thing I want to do is just do a console log here with a couple Expressions let’s say if 10 we’ll say if 10 is greater than 20 which we know is false double Ampersand which is and and let’s say 30 is greater than 15 which is true if I save this we’re going to get false because when we use the double Ampersand in this in this way all everything here has to be true okay because it’s this this expression and this expression and we can add more in here as well like we’ll say uh let’s say 40 is greater than 30 which is true if I save this is still going to be false I could add a million more true things it’s still going to be false because this first one is not true if I change that to 10 is less than 20 which is true which makes them all true then we get true for this whole thing now when it comes to the or operator let’s say if 10 is let’s say 10 is greater than 20 which is false and then I’ll use the double pipes which is the or and then 30 is greater than 15 which is true if I save that we get true even though the first one is false one of these is true which is what matters it’s one or the other so if I make both of these Falls like say 30 is less than 15 then we get false okay so with the double Ampersand they all have to be true with the or just one of them has to be true now you’re going to see these used in in other ways as well so I’m going to create a variable here and actually let me just put a comment because we’re going to look at doubling ever since and this will return so if we add a bunch of values and we use this operator this will return the first falsy value or the last value so let me show you what I mean if I do a console log a and then I’m going to set here a equals let’s say 20 uh 10 double Ampersand 20. if I save that I get 20. so if we read this again we’ll return the first falsely value or the last value we have two values here 10 and 20 none of them are falsy so it’s giving us the last if we do another double Ampersand and we do 30 that’s going to give us 30 because again no falsy values so it gives us the last if I change this 20 to a zero which is falsy then we’re going to get that zero all right if I copy this down and I do before that zero let’s say an empty string which is also falsely then I’m going to get that empty string so that’s how that works now you might be saying well this doesn’t look you know when would I do this when would I use this so to give you uh kind of a a practical example let’s say we have some posts usually it’s an array of objects but let’s just say there there’s some strings post one pose two okay and let’s say we’re getting those from a database or from an API and we want to show them on the page right let’s say we want to show the first post so I’m gonna I’m just going to do a console log you’d probably show this on in the page but for now let’s just do a console log of posts and let’s get the first one all right so I get post one right I’m getting the zero index of this array now if this PO if this was empty like let’s say there’s no posts in the database or whatever and then I go to display this or in this case log it I get undefined so if we were displaying this on a web page you’re not going to want to display undefined so what we could do is before that is add a condition of let’s say posts dot length and let’s say if that is greater than zero then we’re going to use the double Ampersand here now if I save that it’s not going to show this if this if there is no post there right if the posts are empty then it’s not going to show it if I add in here post one post two and then I save now I see post one so this is a very common way of of using this operator we do this a lot in react in the front-end framework react when we’re working in jsx and we’re taking stuff from an API or wherever the the data is coming from and we want to we don’t want to display something that’s not there you want to check first to see if it’s there so if this is false it’s going to show it’s going to return the last value now as far as the double pipe the or operator the way this works is it will return the first truthy value or the last value so let’s say let B and then we’ll console log B and let’s set b equal to 10 and then we’ll use the double pipes and then 20. so in that case it gives us 10 because again it will return the first truthy value or the last value both of these are truthy so it’s going to return the first one if I were to set b equal to let’s say 0 which is falsy and then put 20 on this side then it’s going to return 20 because it will return the first truthy or the last value if I do let’s say b equals and then 0 and then null and then let’s do an empty string which are all falsy it’s going to return the last okay if I put on undefined which is also falsy then it’s going to return that which is the last now as far as other operators we have the What’s called the nullish coalescing operator which is the double question mark it’s not used as much but it is available so the way this work works is it Returns the right side operand so whatever’s on the right side when the left is either null or undefined so let’s say let’s let’s see and console log C and then we’ll do C equals and then 10. the knowledge coalescing operator 20 and it’s going to give me 10. so again it Returns the right side when the left is null or undefined 10 is not null or undefined so it’s going to return 20 the right side if we were to set the left side to either null or undefined then the right side gets returned you can see we get 20. let’s say 30 and let’s do undefined we get 30. now it’s not falsy on this side then it Returns the right it’s just null or undefined so if I do 0 here it’s going to return the zero it’s not looking for just falsy it’s looking for on null are undefined if I do an empty string then it’s going to return that empty string because it’s not null or undefined all right so the there’ll be places where you run into this stuff and keep this you know keep keep the documentation and the code that we write here so that you can look back at it if you need to all right now in the next video we’re going to look at logical assignment all right so now we’re going to look at logical assignment operators and in the last video we looked at logical operators like and and or but we also have assignment operators which look like this so we have the or equals the and equals and then we also have something called the nullish coalescing operator now some of these might not make a lot of sense to you right now because you you can’t really understand where you use them I think that the or the or assignment operator is the most useful here so basically the long version of this I’ll just do an if statement here and let’s define let a and we’re going to set that to any falsy value so we’ll just we’ll just set it to false all right and then in here I’m going to say if not a meaning if it is a falsy value right because it was saying not then let’s set a to whatever let’s say 20 or let’s say 10. okay so this can be useful because you want to check to see if a variable is false or null or anything falsy and if it is then you want to set that to a specific value so the shorthand way of doing this using just the or operator and like we did in the last video we could say a equals and then a or 10. so what we’re saying here is just the same thing we’re doing here if a is falsy then set the right hand side so as you can see it says assigns the right side value which is this only if the left is a falsy value which right now is set to false all right so if I comment this out and I run the if statement all we need to log it you’ll see we get 10. if I comment this out and then I run this it does the same thing we get 10. well there’s a shorter way of doing this using the assignment operator so instead of doing that I can just simply say a and then or equals and then 10. if I comment this out we get the same thing all right if I set this this a to null it’s going to it’s going to get set to 10. if I set it to 0 10 so anything falsy if I set a to 20 then it’s going to stay at 20. this isn’t going to set set it because it’s not a falsy value all right so that that can be pretty useful now with the and assign operator it will assign the right side value only if the left is a truthy value so you probably wouldn’t use this one as much but let me give you the the long version of what we’re doing so we’ll set a variable here let’s say let B and we’ll set that to 20 and we’re going to say if B so if it’s truthy then we’re going to set B to something something else let’s say well you know what we’ll do is we’ll set this one to 10. all right and then let’s console log B and it’s going to get set to 20 because B is truthy again this will assign the right side value only if the left is truthy so using a logical operator we would do B equals B and then the and operator and then 20. okay so if I save that we get 20. this is the same as this and then to make it even shorter we could use the assignment operator so we could say B double Ampersand equals 20. okay same thing but again this probably isn’t you’re not going to use this as much as this because this makes more sense right you’re checking to see if it’s if it’s falsy then you’re setting it here you’re checking to see if it’s truthy and then you’re setting it and there are cases where you could use that now the this right here the double question mark equal this is the nullish coalescing operator so this will assign the right side value only if the left is null or undefined with the or it’s if the left is um is falsy at all so zero an empty string no undefined false so it’s checking for falsy this will only check for null or undefined which you might want you know you might not want to check for zero or an empty string or whatever so the long version of this would be if let’s set up another variable here called C so you’ll say let’s C equals and we’ll set it to null and then we’re going to say if C is equal to null or c is equal to undefined then we want to set C to whatever we’ll say 20. okay and if we come down here we console log C we’re going to get 20 because C is null if we set C to undefined it’s going to be 20. if we set C to false which is a falsy value but it’s not null or undefined then we’re going to it’s going to stay false okay and then the shorter version for that would be C equals and then we want to say C and then the nullish coalescing operator and then whatever 20. so that’s still false if I change this to null then that’s going to change to 20. and then the shorter version of that would be to use the assignment operator like that okay so hopefully that makes sense and it’ll probably be a while before you use something like this in an actual project but I we’re going over you know logic and control and and conditionals so in in different operators so I wanted to include logical operators as well as these logical assignment operators all right so now we’re going to look at something called the ternary operator which you’re probably going to use all the time and it’s a shorter way for writing a conditional so what I’m going to do here first is do a just a basic condition using an if statement and then I’ll show you how to do it with uh with a ternary operator so let’s say using and if statement so I’m going to say if the age variable is greater than or let’s say greater than or equal to 18. then let’s do a console log and we’ll say you can vote else then we’ll console log and say you you can not vote all right so pretty simple if I run that we get you can vote because I set age to 19. if I set it to 13 and say if we get you cannot vote so I want to show you how to write this in a one line one liner using a ternary operator so let’s say using a ternary operator now this syntax is actually really simple but it can it does confuse a lot of people when they’re they’re first learning it so I’ll try to explain it the best I can so there’s basically three parts to it the first is going to be the condition so in this case we’re testing to see if age is greater than or equal to 18 okay so that’s what we want to evaluate then we want to use the ternary operator which is simply a question mark and you can think of this as the if because what comes after this is what you want to happen if this is true right so in this case we want a console log and we’re going to say you can vote right and then for the else is that’s going to be represented with a colon all right so else then let’s do a console log and we’ll say U can not vote if I save that we’re going to get the same result as this all right so three parts we have where we evaluate the condition we have what will happen if that’s true and then what will happen if that’s false so it’s really simple and if I change the age to 20 then both of those should say you can vote now in a lot of cases you’re going to set a value based on a condition you’re going to set a variable value based on it so let’s put a comment here we’ll say assigning a conditional value to a variable using the ternary operator so let’s say we have a variable we’ll call it can vote and we want this to contain we could set it to true well yeah we’ll set it to we’ll make it a Boolean but we want that to be true if the user is 18 or over and we want to be false if they’re under so first thing we want to put here is the condition so let’s say if the age is greater than or equal to 18 then we want our ternary and then next is what we want to put what we want to store in that variable so we could store a string that says you can vote but I’m just going to put a true here because I want that to contain a Boolean all right and then else then we want it to contain false so let’s go ahead and console log can vote and if I save that we get true and then if I change that to let’s say 17 then we get false and it doesn’t have to be a Boolean that you put here you could you could also let’s make this canvo 2. you could have a string that says you can vote and then if it’s if that condition doesn’t pass then we’ll have a string that says you can not vote okay so now if I console log can vote 2. then it has this string you cannot vote that string has been assigned to this variable so you’ll see you’ll see this a lot in all areas of JavaScript now we can also have multiple statements so if we want to do multiple things if we want to do multiple things within the if and the else we can do that as well so first thing I’m going to do is show you the long version of of what I want to accomplish with the ternary so I’m going to create a variable called auth that represents if we’re logged in or not or if we’re authenticated and then I’m going to just create a variable called redirect and I want to set that to something different based on if this is true or false so I’m going to go ahead and just do an if statement first and we’re going to say if off so that’s going to be either true or false if we’re authenticated then I want to do an alert and we’ll say welcome to the dashboard right and then I want to set that redirect variable I want to set that to slash dashboard else then we’re going to alert and let’s say access denied because we’re not logged in and then I want to set that redirect variable to slash login all right and then we’ll just do a console log of the redirect variable here so if I save that we see welcome to the dashboard alert because auth is true so this is going to run and then when I click OK this is going to continue and it’s going to set dashboard into the redirect variable right if I set this to false now if I save we get access denied and we get login put into the redirect variable so we can severely cut down this code using the ternary operator so I’m going to show you how to do that so let me just comment this out and then we’re going to go down here and say const redirect and we want to conditionally set this right so we’re going to evaluate off we’re going to use the well actually I can’t let me just comment that out too so we’re going to evaluate auth whether that’s true or false and if it’s true I want to I want to do two things I want to alert and set the variable so I’m going to put parentheses here and then else I’m also going to do an alert and set the variable so I’m going to put parentheses here so the first thing I want to do if it’s true is my alert so I’ll say alert welcome so I can’t type welcome to the dashboard okay and then I’m going to put a comma after the alert because I want to do multiple things here and I’m going to put in here my string that I want to set which is going to be slash dashboard so that’s the true if it’s false then in here I’m going to do an alert and I’m going to say access denied and then I’m going to put a comma after alert and what I want to set the variable to is slash login so let’s go ahead and save that and you’ll see since auth is false we’re getting an alert that says access denied and when I console log redirect it has login if I change this to true and save welcome to the dashboard and then we have slash dashboard so this does the same thing as this but shorter and its preference when and where you want to use the ternary so let’s see um the last thing I want to show you is that we can use a shorthand we can use the the and operator as a shorthand if there’s no else right because not every if statement not every conditional has an else you might just want to do one thing so let’s say for instance if I come down here um let’s say we want to evaluate off whether that’s true or false and if that’s true then I want to do a console log and just say welcome to the dashboard in my console else then nothing I don’t want to do anything else so in this case if we’re using the ternary oops I’m sorry that should be a colon if we’re using the ternary we need to have an else I can’t just do this if I do that I’m going to get a syntax error so I have to have an ounce but if I don’t want to anything to happen I could do this I could say no right so now it’s going to let me just comment this out because I don’t want to keep getting that alert okay so we see welcome to the dashboard because this is true if this is false then we’re not going to see anything because I just set this to null but a shorthand to this if you don’t want to do else null is to use the double ampersamp the and operator so I can say auth and then double Ampersand and then console.log and then welcome to the dashboard and then I’ll comment this line out and save doesn’t do anything right now but if I set this to true then we see welcome to the dashboard so this this comes in handy a lot I use this a lot when using react with jsx if you don’t know what that is don’t worry about it but it’s it’s very convenient and very compact all right so that is the ternary operator hopefully you understand this so let’s move on to the next video all right guys so most of the stuff that we’ve done has been pretty basic aside from a few things like scope and execution contacts Etc now we’re going to step it up a little bit and learn about loops and iteration as well as some high order array methods which are methods that we can use on arrays that take in a function as an argument and we can use these methods to Loop through or iterate through arrays and do specific operations on each element and these These are methods that you’ll be using all the time in JavaScript so this section is is really important and after this in the next section we’re finally going to get into you know being able to show stuff in the browser and get into the document object model events and all that stuff and now you’ll be more comfortable doing that where now you know the fundamentals of JavaScript syntax all right so let’s get started with loops all right so we’re going to be looking at Loops in the next few videos and a loop is a control structure that provides a way to do iteration in programming and iteration is a process where you repeat something over and over again until a certain condition is met or until a certain condition is not met and this can help automate tasks and so on and there’s many different kinds of Loops in programming what we’re going to look at right now is one of the more common ones and this is a for Loop all right so this is the syntax right here this is an actual code but this is how it’s formatted and I’ll create a real for Loop in a second but just to show you what goes in here so we have four and then we have some parentheses and three different Expressions that are separated by semicolons which are a little weird you probably mess up and use commas but it’s going to be semicolons here now the initial expression is where we initialize a variable or counter to use within the loop and then the condition expression is going to be the condition that the loop will continue to run as long as that condition is met so as long as this is true it’s going to run once it’s false then the loop will no longer run and then we have the increment expression which is going to be executed after each iteration of the loop okay every time it Loops that’s called an iteration it’s going to run after every one of those and it usually increments the variable because if you keep your your variable or your counter the same you’re going to have an infinite Loop you need to increment that and then the statement is just going to be your code executed and you need to use curly braces like you would a functioned to execute a code block all right so let’s just comment that out because that will break our script and then we’re going to come down here and let’s create a for Loop okay so just like a function parentheses and curly braces then we want our initial expression which I’m going to say let I I is very common very common variable to use in Loops so we’ll say set that to zero then we want to put our semicolon because these three expressions are separated with a semicolon the condition that I want this loot the code to run as long as this is met is going to be as long as I is less than or equal to 10. okay so as long as that condition is met this Loop will run and then lastly here I’m going to put in the increment expression which will be I plus plus so we learned about that in the past video this will just increment by one all right so basically it starts at zero it’s going to go through then it’s going to increment by one so I will then be equal to one it’s going to go through again it’s going to run whatever code we put in here every time up until this is no longer true so let’s just do a console log in here I’ll just put a string we’ll say number and then I’m just going to concatenate on the I variable and we’ll save that and run it and you’ll see we’re going to get number zero all the way up to number 10. now it stops here because it it no longer meets this condition it goes through the this last time and says well now I is is doesn’t match this it’s not less than or equal to 10 so we’re not going to run this again okay if I change this to 11 and save then it’s going to get it’s going to go up to 11. if I change this initialization here from 0 to let’s say five and then I save it then it’s going to start at 5. all right uh and it’s gonna it’s gonna just increment by one each time if I wanted to I could do something like I equals let’s say I plus two if I save that then we get 5 it’s going to skip six seven skip eight nine so it’s basically incrementing by two but most commonly you’re gonna see this and let’s just set that back to zero and let’s set this back to 10. now you might be asking why I’m using let because you know that I use const unless I I can’t so in this case if I were to use const here and save that I get assignment to constant variable because remember we’re initializing I here is zero but it’s going to get changed in every iteration so we can’t have this as a constant we use let now I also showed you in a past video that we have block scope here right so if I come outside of the loop and I console log I I’m going to get an error unless I use VAR because remember VAR is not block scoped so if I do that then I’m going to get 11 but I would highly recommend that you use let when you use when you you know create for Loops now you’re going to have situations where you check to see if I is is equal to something or greater than or less than something and maybe do something else based on that so for instance if I want to say put in an if statement here and if I say if I is equal to 7 and then let’s say I just want to output and say 7 is my lucky number so I want to Output that if it’s seven and then if I didn’t want number seven to show I just want this 7 is my lucky number then I could put an else and then move this into here so now if I save that it’s not going to show number seven it’s just going to show 7 is my lucky number instead now there will be times where you will Nest Loops so I’m just going to show you that real quick and it can get a little confusing when you have you know multiple levels of Loops but just to give you a simple example let’s do the same thing here where we set I but let’s set it to 1 and say as long as I is less than or equal to 10 and then I plus plus we want to increment by one and we’ll do the same kind of console log thing here but still within this Loop I’m going to open up another for Loop now when you do this you want to make sure you don’t use I again you want to use something different and it’s common to use J so we’ll say let J equals one I’m going to do the same condition here I’ll say as long as I is less than or equal to 10 and I’m sorry j you don’t want to do that you want to do J yeah or else you’re gonna get an infinite infinite Loop and then let’s increment J and then in here what I want to do is show I want this to do the console log like we already have here starting at one and under each number here I want to show that number times one that number times two all the way up to 10 that’s what this represents right here so let’s console log a string that actually says like one times one equals one in one times two equals two Etc so we’ll use a template string here and I’ll say I and then we’ll just put a asterisk here times J and then an equal sign and then the actual expression to to be evaluated is going to be I times J so if I save that what we’re going to see is the well actually let me comment this one out we’re going to see number one and then under it one times ever all the way up to 10 then 2 and then two times all the way up to 10 and that’s because of this if I change this 10 to a 5 then it’s going to show 1 times 1 all the way up to five for each of these all right and we could do as many as we want if I put this first one to a hundred it’s going to show me all the way up to 100 and it’s very fast so that’s a nested Loop so let me actually should say nested loops and what I want to show you now is how we can use a for Loop to Loop through an array now I don’t do this very much because there’s a for each method that we can use it’s a high order array method we’re going to get into in a couple videos from now that we can use to Loop through arrays and do the same thing but it is possible to use a for loop as well so let’s say we have names or whatever anything you want to put into an array I’m just going to put a bunch of strings here names and we’ll say John and I don’t know Tim okay so we have some names now to Loop through this I’m going to say four I’m going to initialize my variable so we’ll set let I set that to zero and then here for a condition we can say as long as I is less than is less than the length of the array so we’ll say names dot length and then we need to increment I so we’ll say I plus plus and then within here we can access each one by its index I is now going to represent its Index right because it starts at zero so this will be zero then that’ll be one two three and four so let’s just console log each one we’ll say names and then we’ll put the I as the index in here and I’ll save that and now you see it’s going to Loop through and it’s going to show each name now those of you that are just learning this for the first time I want you to try a little challenge so pick a name here let’s say Sarah and instead of just printing Sarah have it print Sarah is the best so if you want to pause the video and try that out you can do that now but basically all we have to do there’s a few ways we could do it if we know the index which we do we know Sarah is in the zero index so we could just say if I is equal I’m sorry the two index if I is equal to 2 then let’s do a console log and we’ll just say names I which is just going to say Sarah and then we’ll concatenate onto that a string and say is the best else then we just wanted to log the name so I’ll put this up here oops whoops and save and now it says Sarah is the best so you could do it like that you could test for the value so we could say if names and then I if that is equal to and then the value let’s say we want to do John is the best then we can check for John and now you see it says John is the best all right so that’s pretty much the basics of for Loops now you’re probably going to have times where you run into something called an infinite Loop that’s a loop that just keeps going and never stops until it crashes your browser in this case and that can happen if you mess up the condition or if you if you forget to increment if you want to test it I wouldn’t recommend it but if you want to test it you’ll just have to most likely force close your browser but you could put Infinity here so if I did that obviously I is always going to be less than infinity that means that this is always going to run but I’m not going to do that so you probably will run into Infinite Loop set some point or another but in the next video we’re going to talk about the break and continue statements all right so now we’re going to look at the break and continue statements so this should be a pretty quick video basically what break does is it allows us to do just that break out of the loop so usually you’re going to check for a specific condition and then you’re going to break out so let’s say we’ll set I to zero let’s say as long as I is less than or equal to 20 and increment by one and then let’s say we’ll just do a console log of I if I save that you’ll see it’ll just show 0 through 20. but let’s say we want to stop once we hit 15 so I’ll just do a check here and say if I is equal to 15 then we’ll console log and let’s just let’s just say breaking and then right under that we’re going to put our break statement so just break semicolon we’ll save and now you can see once it hits 15 it’s going to break and it it just doesn’t go on any longer alright so you might have cases where once you hit a certain condition there’s no need to keep going you just break out of the loop all right now I’ll continue is a little different so with continue continue basically you can you can skip uh the rest of the code in a current iteration and then continue to the next iteration so for instance if we do the same thing here we’ll say let I equals 20 and as long as I’m sorry let I equal zero and then as long as I is less than or equal to 20 we want to increment and we’ll do the same thing just console log I let me just uh let’s comment this out here okay so we just get 0 through 20 and let’s say where a superstitious hotel and we want to skip the 13th floor so let’s say if and say I is equal to 13. then let’s do a console log and we’ll say skipping 13 which I think is crazy and then we want to just continue all right so what’s going to happen here if I save this as you’ll see it’s going to skip 13. so instead of like I could I could have the same effect if I did this if had this console log and then else had this console log but here I’m I’m just going to skip the rest of this right so whatever is going on down here it’s going to skip because of this continue so here it breaks out of the entire Loop right here it breaks out of the iteration and then continues on okay so hopefully that makes sense all right so now we’re going to look at two more types of Loops the while loop and the do while loop and these along with the for Loop are kind of like old school ways of doing iteration now that we have high order array methods we have four each and then there’s also other Loops like four in and four of which I’m going to go over as well but it still is essential that you learn these because these are like fundamentals and not just in JavaScript in just about every language so with a while loop it’s a little different because all that we put in here is the condition when we initialize and increment the variable we don’t do it within these parentheses this is just the condition so I’m going to initialize the I variable outside of the while loop and then in here I’ll put the condition say less than or equal to 20. and then I’ll console log let’s just put a string number and then concatenate that number now this can be easy to forget the increment and then have an infinite Loop because it’s not as obvious whereas a for Loop you know you have the three parts to pass in here you just have to remember to increment so let’s save that and now it’s going to print out 0 to 20. okay so that’s the syntax of a while loop now for many cases you could use either a while or a for Loop and achieve the same result as you can see it’s very similar it’s just different syntax but a common rule that many programmers follow is to use a for Loop when you know the number of times that you want the loop to run and then to use a while loop when the number of times the loop will run is unknown okay that’s not a mandatory convention or anything but that’s something a lot of people do we can also use while Loops to Loop over arrays just like we could use for Loops I’m just going to comment this one out and then let’s say const array we’ll set that to let’s say 10 20 30 40 and then in here we want our condition expression so let’s say while I is less than the array Dot length then we’re going to console log and we’ll say array we want the index to be the I variable and then this is really important you want to add your increment are you going to get an infinite Loop so if we save that now we’re going to see 10 20 30 40. so it’s printing out the values of this array if I add 50 that’ll get added as well now another thing that we can do is Nest while Loops just like we can for Loops so let’s say Nest nesting while loops and we’ll do the same thing we did before we’ll have the multiplication thing so let’s use I so we’ll say as long as I is less than or equal to Let’s do 5. and then in here we’ll just console log we’ll say number and plus whatever that I variable is and then in here I need I’m going to Nest another while loop so I need another variable right so we need to initialize another variable so I’ll use J and set that to 1. and then let’s say while and we want to say while J is less than or equal to and this is for the multiplication part so let’s do five we’ll do up to times five and then in here we’ll do our console log and we’ll make this a string where we can say I times J is equal to the expression of I times J now this is really important we need to remember to increment both J and I so let’s say J plus plus and then back outside into the parent Loop we want to do I plus plus all right so let’s go ahead and try that and now you’ll see it’s going to Loop through five right one through five actually it’s going to start at zero because of this we can set that to one so now it’s going to start at 1 and it’s going to show one times one through five then two two times one through five three four and then 5. okay so that’s how we can Nest a while loop now do while Loops are a little different because the do while loop will always run at least once even if the condition is false so the answer to the question when would I want to use a do while loop is when you always want the the block of code to run at least once even if the condition is never met so let me show you what I mean I’m going to comment this out and then let’s do let’s say do so this is the syntax we we say do no parentheses after it just just uh curly braces and then whatever we want to happen let’s say console log and number and concatenate that and then we want to increment so I plus plus and then here is where we’re going to add while and then that’s where we want to add our condition so let’s say while I is less than or equal to 20. okay and I don’t know why I open parentheses here um for curly braces we don’t want those all right so this is a do while loop so let’s run this and as you can see we get we get 1 through 20. remember this is set to 1. now like I said the thing with this is this code right here is always going to run once even if this is never true so if I were to come up here and set I to 21 that this is this condition is never met however if I save this I get number 21. so it runs this code here no matter what so that’s that’s the big difference with this if I uncomment this uh where is it this right here where it says I is less than or equal to 21 and I comment out the do while and save we get nothing right because this condition here is never met this is 21 so this is not whoops this is 21 so this is never going to run or this code is never going to run do while it’s going to run once then it’s going to check and see if it’s to run again so that’s the big difference and and you can also use break and continue statements with these Loops as well just like you can with a for Loop all right so when you go to get a job as a web developer and you go to different interviews you may be given specific programming challenges to do on the computer or on a whiteboard and it’s good practice to do challenges like this not only for job interviews but it also just sharpens your skills in general and you’ll find that most challenges have some kind of iteration involved and one of the most common ones that you’ll run across is called fizzbuzz and this has to do with loops and conditionals so I think that this is a good point in the course to do the fizzbuzz challenge and it’s not very difficult we’ve we’ve already gone over everything that you need to know so as far as instructions you need to print or log the numbers from 1 to 100 you guys know how to do that easily and you can use different types of Loops if you want you can use for a while whatever and then for multiples of three you want to print Fizz the word Fizz in a string instead of the number for multiples of three for multiples of five you want to print the word Buzz okay instead of the number and then for numbers which are multiples of both three and five you want to print Fizz Buzz okay so as far as hints go if you’ve taken the course up to this point then you know how to write a loop and output or log something for each iteration right so you can print the numbers you also know how to check for a condition with if else else if you also know how to get a remainder of a number using the modulus operator which is the percent sign and this is really all you need to know to complete this challenge I probably already told you too much now if you don’t get it don’t worry about it some people including myself are not that great with these types of challenges especially if you can’t you know do any research so try not to go and and Google fizzbuzz challenge try this on your own and see if you you can figure it out all right so let’s get to the solution now I’m going to show you I’m going to show you how to do this with a for Loop and a while loop so first thing we want to do is print or log the numbers from 1 to 100 which is very simple so we’ll say 4 and let’s initialize I with one because we’re doing one to a hundred the condition is going to be if I is less than or equal to 100 and then we want to increment I by 1. all right and now in here for now let’s just console log I so it should just print 1 to 100. so the next step is to print uh print the word Fizz for multiples of three now the way that we can figure out if it’s a multiple of three is if if the remainder is zero and we can find the remainder using the modulus operator so here let’s say if and we’ll say if whatever that the current number is on the current iteration and then modulus 3 if that is equal to zero then we know it’s a multiple of three so in that case we’re going to console log Fizz and then let’s just do else and then we’ll move that console log of the number in there so if I save that and we come up here you’ll see that three is Fizz 6 9 12 15 and so on now if it’s a multiple of five we want to print the word Buzz so what we can do is put let’s go right here and say else if or l space f and then open up a curly brace and end our curly brace and then in here we want to say if I and then again we’ll use the modulus operator but 5 this time if that’s equal to zero then we want to console log the word Buzz so let’s save that and now if we look you’ll see that 5 is Buzz right 10 is Buzz but if we look at 15 it says Fizz and that’s because 15 is a multiple of three and five and since this conditional was first then it’s going to log Fizz so for the condition of of looking for them both we can’t do that under these ones because it’s going to check those first so we have to make sure that the first one we check is is for both right so what we’ll do is instead of putting this as an if we’re going to make that an else if and then we’re gonna it will just push that over and then we’ll have our initial if statement here like that and then we can say if I modulus 3 equals zero and if I modulus 5 is equal to 0 then we want a console log Fizz Buzz alright so save that and now if we look we’ll see 3 is Fizz 5 is Buzz 6 is Fizz nine is Fizz 10 is Buzz 12 is Fizz fifteen is fizzbuzz the next one after that should be 30 is fizzbuzz next one after that should be 45 is fizzbuzz all right now a shorter way to do this since 3 times 5 is 15 that means that any uh anything that’s divisible by 15 is is also going to be divisible by both three and five so we can actually shorten this to just say I’m sorry that’s not what we want we want that to be zero but we want this to be 15. all right if I save that we should get the same result so Fizz buzz and then 15 fizzbuzz 30 fizzbuzz 45 fizzbuzz 60 say and so on all right so that’s the solution with a for Loop now a while loop is going to pretty much be the same thing we’re going to have the same conditions it’s just formatted a little different so let’s say while loop and remember with a while loop we need to set the variable outside of the loop I’m going to use J for this since we already used I and I’ll say even though I was scoped but I’ll say let J equals 1. and then we’ll say while J is less than or equal to 100 then we want to do this this block right here so I’m going to grab that paste that in now remember with a while loop it’s it can be a little hard to remember that you have to increment so make sure that you go outside of that if and you just increment I by one so I plus plus all right so let’s save that uh whoops I’m sorry that should be J so here yeah let’s change that change that to J that and that and this all right so now actually let me comment out the for Loop so that doesn’t run and we should get the same result so three Fizz six five Buzz six Fizz get to 15 we get Fizz Buzz we get to 30. we get Fizz Buzz okay so this is how we would do it with a while loop but basically the same thing it’s just a structured in a different way all right so if if you got it great if you got it and it’s it’s a slight different slightly different from mine that’s fine if you didn’t get it that’s fine as well um you know you’ll you’ll learn more as we move along all right so in this video we’re going to look at a four of loop which is a newer way to basically Loop through iterable objects like arrays or any even strings and maps and sets which we haven’t talked about yet not object literals there’s actually another loop called a four in that we’re going to look at in the next video to show you how to Loop through objects but this is a cleaner way to Loop through an array than a standard for Loop or a while loop so let me just create an array here we’ll just do items and we’ll put some random items in here let’s say Book Table chair and kite and then I want to Loop over these now if you remember with a for Loop what we would do is we would initialize a variable here set it to zero and then we would do as long as I is less than whatever that array length so items dot length and then we would increment that I variable and then if we want to access each specific item we would have to do items and pass in the the variable as the index all right now A Cleaner way to do this is with four of so instead of doing all this in here we can simply do I’m using cons but you can use let if you want but we can simply say const and then give a variable name for each individual item which I’ll just call Item and then say of items all right and then in here I don’t need to do this because we can just simply access the item variable if I save that and run it we get the same result and this is much cleaner and just much more modern looking and if we wanted to have an array with objects in it like let’s say users and we’ll set that to let’s say an array of objects and we’ll just give these a name so we’ll say name Brad and a couple more here I’ll say Kate and say Steve all right and then let’s comment this out and we’ll say four and we’ll call we’ll say for const user of users and then I’ll console log user okay so now we have all of our objects if I want to access a specific property then I would do user Dot and then whatever that property in this case name now my first choice for looping through arrays is to use the for each method which is a high order array method that you can use on that you can use directly on arrays but I think this is a better way to do it than using a standard for Loop or a while loop or a do while loop or anything like that so we can also use this to Loop over strings okay let me just put a comment up here and I’ll say Loop through arrays all right now for Strings let’s say const and we’ll just say Str and we’ll set that to let’s say hello world and then if I want to Loop over that I can simply do four and then give a variable let’s just say letter because that’s what we’re going to get is a letter and then of our string and then if we console log here letter and save then you’ll see it’s going to Loop through and it’s going to Output each letter of that string another thing you can do is Loop over Maps which we haven’t talked about yet I’ll get into this later on but just to give you a quick example we can create a map a variable called map and set it to a new map not a nap although I could use one of those but we’ll set it to a new map and then we can add key value pairs so I could do map.set and we could set let’s say name to John and then I could Set Let’s do an age so we’ll say age 30 and if I wanted to Loop through these I could do a four of so I would do cons now we can get the key and the value by putting brackets in here and just saying key value of the map and now if I console log here I’ll go ahead and log both the key and the value and now you’ll see down here both the key value pairs name John and age 30. so you can use it to to Loop over Maps as well pretty much any iterable object now there is another type of loop called for in that allows you to Loop through object with object literal values which we’ll talk about in the next video all right now there may be times where you want to actually Loop through an object’s values and we can do that with the four in Loop so let’s go ahead and create an object here I’m just going to call this color object and set that to some curly braces and then we’re going to do color one set that to a string of red and we’ll do that for a few colors let’s say color 2 is going to be blue say orange would be color three color four we’ll do green all right and we want to Loop through and get these colors so a four in Loop is very similar to a four of loop so we would just say four and then inside here we’re going to say const and we can get the key so if I do key in color object and then we console log that key we get color one through color four so we get the keys now if we want to get the value all we have to do actually we’ll just log it here is take the color object variable and then pass in here the key if I do that then you can see we get the values red blue orange and green now let’s say we want to use this with an array because we can we can use four in loops with arrays so we’ll say const and say color array and we’ll set that to an array with red green blue and let’s say yellow all right so we have this array of colors and I’m going to do this so we’ll say four and then we’ll do cons let’s say color uh not of we’re going to do an in so in the color array and then let’s console log color if I save that we’re actually going to get 0 1 2 3 instead of this so what’s happening here is it’s giving us the keys okay it’s giving us the keys which are in this case these are going to be numeric Keys 0 1 2 3. so we can still get the values of an array here but what we have to do is let’s change color let’s change that to key and then we can say color array and then just pass in the key like that if I save that and run it now you can see we’re getting the values of the array so you can also there’s so many different ways to iterate through arrays but this is most commonly going to be used if you want to get the the either the keys and or the values of an object literal so now in the next video we’re going to start to look at high order array methods which are extremely helpful and you’re going to be using them all the time within JavaScript and we’re going to start with four each all right guys so now we’re going to get into high order array methods in this particular video we’re going to look at four each but there’s a lot of these that can do different things now they all work in a similar way in that they take in a function as an argument which this is called a callback function and in that callback function we can pass in a variable for each element in that array or each item in that array now what a 4-H does is it just simply Loops through it doesn’t return anything it just Loops through as if we were using a 4 or a four of loop to just go through the array and do something specific all right so let’s go ahead and jump in here and we just want to create an array of some sort I’m going to call this socials and I’m just going to have a bunch of strings in here so Twitter let’s say LinkedIn do Facebook and let’s do Instagram all right so we just have an array of strings and this could be an array of anything and before I show you the four each I just want to console log here socials and then the Prototype chain which is double underscore Proto double underscore and I think I showed you this back when we looked at some of the simple methods like push and pop so you can see that those are here as well so any any methods or properties like length on the array are going to get shown here and you can see we have four each right here we have map map filter find reduce these are all high order array methods and they work in a similar way so basically let’s go ahead and comment that out for now basically what happens is we call the method so in this case four each and then that method is going to take in a callback function okay an anonymous function it’s not going to be named and we can do that in a few different ways we could just use the standard function syntax and then what gets passed in here if we look at this documentation page here what gets passed in you can call it element like they did here but you can call it anything it just represents each item in the array okay so here we just have ABC for us we have these strings here so you can call it I mean a common thing I’ll do is call it the singular version of the array or I’ll call it item I don’t usually use element but again you can call it whatever you want and then you have access to that in here so we can do console log item okay so this this function right here that we pass in is going to get run for every element or every item that we have in the array so in this case it’s going to get run four times and what we’re doing is just logging it to the console so if I save that and we take a look we should see these in the console all right and if you want to kind of slow it down a little bit you could go to sources and go to script okay we looked at this debugger back when we looked at execution context and the call stack but what I’m going to do is put a break point right here on the four each and then I’m going to reload the page okay so it nothing is run yet but if I come down here to the step arrow and I I hit that and then it’s going to go into the function we’re going to run the four each I’m sorry run the console log and now we get Twitter okay if I go back again it’s going to run console log again because there’s another item in the array again Facebook again Instagram and then it’s going to end because there’s no more items in the array okay so that’s kind of a step-by-step of what’s Happening let me just remove I just want to remove that break point there all right and then we’ll go back into the console now like I said you could pass in a function this way or let’s actually comment that out or you could first of all get rid of the function keyword and then add on our Arrow so this is valid but since it’s just a one line expression we can actually take away the curly braces as well if I save that we get the same thing now in addition to the item that we pass into the Callback there are some other arguments that we can pass in so I just want to go back here and we’ll come down so these are the parameters right we have our callback function and then in that callback function we have the item our element but in addition to that we can also pass in the index of the current element being processed in the array and of course it’s going to start at zero the array so we can also get the entire array there might be times where you need that within your your function so let’s go ahead and pass in the index and then we’ll pass in the entire array so those are the additional parameters so here what I’ll do is I’ll console.log let’s just put in some backticks here and of course we need to wrap the item in that and then let’s also do before it will do the index and then slash so we’ll say index Dash and then the ice Dash not a slash and then if we look here you can see the index starts at zero and then increments and then let’s pass in after the back tick here we’ll just pass in the entire array so you can see that you have access to to that as well now you can also pass in a named function rather than an anonymous callback so for example let’s create a function called log socials and that’s going to take in an item or we can just say like social and then we just want to console log social so we want this function to run for every item that’s in the array so what we can do is just take socials call for each and then simply pass in log socials all right if I save that let’s just comment this one out if I save that you’ll see it’s going to log all the social items here now when you pass this in you don’t want to execute it right you don’t want to pass in the the parentheses you want to just pass in the definition of the function just like you do here you know you don’t you don’t execute this function here it’s a callback now the last thing I want to show you is with objects because usually when you pass when you use for each it’s usually on an array of objects so let’s say social objects and we’ll set that to an array and each object will have let’s say a name say Twitter and the URL say https twitter.com and then what we’ll do is copy this down a couple times and let’s change this one to Facebook and what else LinkedIn and Instagram all right and and you can have I think I think I mentioned this before but you can have trailing commas in your arrays in fact if I save prettier automatically keeps the trailing comma so I want to comment this one out and then I want to log each item here so let’s say social objects and then Dot for each and then we’re going to pass in our function which is we’ll say item and then let’s just do uh console log of that item so in this case it’s going to give us objects right each each item in the array is a social object so if we want to access a specific property specific property we would do item Dot and then whatever let’s say URL so now it will give us all the URLs and then of course we could do whatever we want to that array and we’ll be using for each a lot more but in the next video I want to show you an example of another high order array method called filter okay so now we’re going to look at filter which is another high order array method for each is usually the first one you learn now the difference between four each and a lot of these other ones we’re going to look at like filter and map is that filter along with a bunch of other high order array methods actually return something in most cases they’re going to return an array now our modified array so if we look at this example at on mdn you can see we have some words in an array and then we have this variable result set to words.filter so this is something that you’re going to do because this returns something right for each does not so you’re typically not going to see a variable equal to something dot four each you just run that for each and then you do whatever you want in the function in this case what’s going to happen is we pass in a function okay this is a function I know it looks a little weird because there’s no parentheses around this but remember with arrow functions you don’t need to have parentheses if it’s just one parameter so what we’re saying here is We’re looping through we get can get each word and then we’re testing that word and seeing if the length is greater than six Okay now what’s this is going to return this line right here is an array with only the words that pass this test or only the elements in the array that pass this test so the result will be these words right here because they’re greater than six if they’re not then they’re not going to be put into that array so we’re filtering out the words that don’t pass this test okay so let’s uh let’s try this on our own so that it’s more clear so we’ll say cons numbers and I’m going to set this to let’s just do one through ten nine and ten and then let’s say I want to filter out and I only filter out all the odd numbers so I just want the even numbers now I’m going to create a variable because it’s going to return something so we’ll say let’s say even even numbers and we’re going to set it to the numbers array dot filter and again this will take in a function I’ll just do a long form for now so we can say function and pass in here whatever whatever variable we want to use for each individual element or number so I’ll just say number in this case you could use item or whatever now what we want to do here is return from this function some kind of condition now if I want to get the even numbers I can do this I can say if the number and then modulus operator and then 2 if that is equal to zero so if it’s divisible by 2 then obviously it’s even right if we have zero remainder then it’s divisible by 2. so this is going to Loop through run this test on each of these and whichever ones pass will be put into a new array in this variable so let’s go ahead and console.l log here even numbers and if we take a look in our console you can see we get 2 4 6 8 10. if I add on to this 11 and 12 then 12 should be added now this is kind of the long way of doing this the shorter way let’s say short version and then I’m just going to comment this out so the short version would be to do even numbers equals numbers Dot filter and then we could pass in here just number use an arrow and then we just want uh the condition which is if the number modulus 2 equals zero save that we get the same thing okay now if you wanted to do this with a 4 each let’s say same with four each it’d be a little more complicated right if you want to pause the video and try it you can but let’s um let’s take numbers right and then do a four each so we can’t we’re not going to set like anything equal to this this is just to Loop through so what we can do is initialize a variable here we’ll just say let even numbers and then we can Loop through here and say number and then we’re going to have to do an if statement here if we want to test right so we’ll say if the number modulus 2 equals zero then we’re going to take the even numbers uh even numbers variable which is is uh you know we want to set this to an empty array so you can see how much more complicated this is then we would have to push onto it the number if it was even right so now if I save and we’ll get the same result so this right here this one line is the same giving us the same as this right here all right and we could use const here since we’re just pushing on we’re not reassigning anything yeah so that’s filter now I want to do this with uh an array that’s slightly more complicated with some other conditions other than just testing for an even number so let’s comment this out and then what I’m going to do is grab the array so we’re just going to use an array of of company objects all right so each company has a name a category a start date and an end date so if you want you can look at this as a challenge and pause the video and try to try to do this they’re all just using filter but the first one the first thing I want to do is get only retail companies okay so I just want companies where the category is equal to retail so if you want to pause the video and try that go ahead and do it now but what we’ll do is create a variable let’s say retail companies and you you can you can imagine how useful this is you know if you think about a UI where you’re filtering things this comes in handy so let’s say companies okay we want the company’s array and we want to filter and then we’re going to use a short form Arrow function so let’s say company so for each company we want to test if the company Dot category because it’s an object so we want to access the category and say if that is equal to the string of retail all right so now if we console log retail companies we should get three three values and let’s take a look here so we have company two company four and Company nine all right so if we look here company two is retail company four is retail and Company 9 is retail so let’s do another one let’s say let’s say we want to get get the companies that started in or after 1980 and ended in or before 2005. okay so companies get companies that started in or after 1980 and ended in or before 2005. okay if you again if you want to try it you can do that I’m going to create a variable we’ll just call it early companies put a space there early companies and we’re going to set that to again companies Dot filter and we should probably comment this console log out all right so companies filter and in here we’re going to have a function pass in our variable of company that’s our item and then we want to test to see if the company dot start is greater than or equal to 1980 right and then is that a string no it’s not a string and okay so we want to use the the double Ampersand the company dot end is less than or equal to 2005. so that should do it so let’s console log early companies and save and we get three so if we look at these it’s company 1 7 and 9. so company one was 1981 to 2004 company seven uh was 86 to 96 and Company 9 was 89 to uh what was it I’m sorry 80 81 to 89. so those were all in the in the realm of 1980 to 2005. these are the ones like this was the 2008 um this one was 2007 2010 so it filtered out by this this condition right here this truth test and then the last one we’re going to do is to get companies that lasted let’s say lasted 10 years or more so to do that we’ll say const and I’ll just say long companies and set that to companies dot filter and we want our function here and it’s gonna I’m gonna say company and then the truth test we want is the company dot end minus the company dot start is greater than or equal to 10 that means that it lasted 10 years or more so let’s console log long companies and let’s let’s comment this log out and you can see we get nine one two three four five six seven eight nine uh oh this should be minus okay so we get five one two four six seven so if we look at like three that only lasted what 99 to 2007 so that’s not quite 10 years what else uh four or five didn’t last 10 years 2009 to 2014. so yeah so hopefully this gives you an idea of how Filter Works this is very useful and we’ll you’ll use it all the time in your interfaces you know when you have a a search box and you’re filtering down by whatever it is location or anything like that this is going to come in handy all right now in the next video we’re going to look at map which allows us to basically return an array just like filter but we can return we can modify anything we want and return an array of anything we want all right so in the last video we looked at filter which is a high order array method and we saw how it returns a new array and it that’s based on a function that returns true or false anything that was true would be put into that array with map this works a little differently where the function what that we pass in can return anything that we want to be put into this new array in this example let’s make it a little bigger in this example we have some numbers in this array one variable and then we’re setting this new variable of map 1 to that array dot map and we’re saying for each value they’re using X here but you could use anything we’re taking that value and multiplying it by two so they’re doubling it and then that will get put into this new array so essentially what we’re doing is taking this array and then we run it through map and then we have an array of these numbers doubled okay so what I’m going to do is give you a similar example and then we’ll we’ll use the same companies array that we used in the last video and do some stuff with that so let’s just create a numbers variable and we’ll set this to we’ll just do one through five and then let’s create a variable here we’ll call it doubled numbers make it a little bit more specific than the the docs and then we’ll take the original numbers array and do a DOT map that’s going to take in a function and we’ll say for each number then we want to return and you could either do the short syntax or you could have curly braces and you could use the return keyword but this is shorter and cleaner so let’s say number times two all right then we’ll go ahead and console log here the doubled numbers and if we go and we look we should see 2 4 6 8 10. now the what I’m returning from eat from this function for each of these elements is each one times two but it could be anything like for instance if I wanted to return a string that had number space and then concatenate the number if I do that you’ll see now it’s going to run through the array it’s going to Loop through and take each one and just prefix it with the string of number so now I have an array of that so you can do absolutely anything here if I wanted to multiply it by 3 and triple it we could do that as well all right now if you wanted to do this with a four each I think it’s useful to know how to do that so let’s say same same with four each so just like we did with Filter when we used a 4-H we have to first just create a variable let’s say double we’ll say double numbers two set it to an empty array and then we could take the original numbers array and loop through so in here we want to say for each number then we’re going to take the double numbers to variable which is an empty array and push onto it the number times two and then if we console log double numbers two uh oh I said doubled oh yeah let’s do double numbers too and now you see it’s the same exact thing so this this line is a shorthand for doing this but now what I want to do is use that companies array that we used in the last video to do a couple things and again if you want to pause the video and do some of this on your own you can do that as well I would encourage that so let’s say we want to get or let’s say create an array of company names okay so just us an array with just the company name no objects or anything just strings so let’s say const company names and we’ll set that to companies which is our array of objects and then we want to map through and have a function where we say for each company we just want to return the company dot name okay so that’ll run for each element each object in the array and get put into a new array so then let’s console log that new array and there we go so now we have just a simple array that has all of those company names inside an array with just numbered indexes now let’s say we want to create a new object that has just the the company and the category so let’s say create an array with just company and category so if you want to pause and try it now you can do that so I’m going to call this company info and let’s set that to companies dot map and say for each company Let’s uh I’m just gonna put a code block here because I’m going to return an object I could just use parentheses and put my object in that but instead I’m just going to say return an object and then name is going to be the company dot name and then category is going to be the company Dot category okay and then we’ll go ahead and console.l log company info and let me just cut let me comment that one out and you can see now we have an array with all of the companies but only the category and the name okay because that’s all we chose and there’ll be plenty of times where you’ll have uh you’ll have a bunch of data but you want to strip some of it out like maybe you don’t need the start and end dates so you can simply manipulate that array or I mean this this will create a shallow copy and then you can manipulate that array to have whatever you want in it now let’s create an array of the length of each company in years so let’s try that we’ll say create an array of the length of each company in years so it’ll just be an array of numbers so for that let’s say const company years and let’s set that to companies.map and we’ll say for each company for each company I just want to take the company dot end date and just subtract the company Dot start date actually you know what let’s make this a little more complicated let’s say create an array of objects with the name and the length of company in years so instead of doing what I just did I think this is a little better this will yeah so we’ll do that we’ll say return an object with the name so we have access to company with all the properties so name and then let’s create a new property called length and that’s where we’ll take the company Dot what is it company dot end subtract the company dot start okay so now let’s do a console log of company years and now we should have objects with the name and the length of year so 23 16 all right and we could even just concatenate in here space years so 23 years 16 years and just to validate that if we look at company one it was from 81 to 2004 so 2001 would be 20 and then we have three more two three four yep so that is correct all right now another thing that you can do is chain let’s say chain map method so you can have more than one map method let’s say we want to square root we want to take a number we want to get the square root and then double it so I’ll call this Square we’ll say square and double and what we’ll do is we’ll set that to numbers dot map and the first thing I’m going to do is is square it so we’ll say for each number we want to use the math object and then we’ll use sqrt so square root that number right so right now if I console log this let’s say Square and double so if I do this right now it’s just going to give me the square root right now I want to double it so what I could do is add an additional map so this map which ends right here just to make this a little cleaner looking I’m going to put this dot map on the next line this is what you’ll commonly see get rid of that semicolon and continue on with a new map which will take in the square root and I could call this number if I want but let’s call it square root because whatever you return from the first map so this is going to be put into this parameter right here so now I’m going to take that square root and I’m going to double it so times two so now if we save that we now have the the square the number square root and then we take that square root and then we double it we multiply it by two all right so hopefully that makes sense and you can have as many of these as you want now just to kind of make it clear on what’s going on here I’m going to do I’m going to give you the long version as well so let’s say const square and double two set that to numbers dot map and what’s going on with passing in a function so I’m just going to put a long version in here and pass in here number right and then what we’re doing from this first function is returning math dot square root and passing in the number okay for each element in the array and then when we we can add the other map so here we’ll say you know I’m going to put this on a new line as well and then we’ll add our new DOT map our next dot map and in here we’re going to put a function and this is going to be the result of the last map which will be the square root so then here we’re going to return the square root multiplied by 2. okay so now if I console log square and double 2 and save we’re going to get the same result so this right here is just a shorter version of this just remember whatever you’ve returned from this map we’ll go in here if I were to have another dot map whatever I return from here we’ll go into there in fact I could say map again and pass in a function and here let’s just say square root doubled and then we’ll return let’s say I don’t know we’ll just let’s multiply that yeah we’ll just multiply that by three and Save oops this should be square root doubled okay I can’t access like this variable this right here the square root I can’t access it here what happens is whatever is returned is going to be put into here square root doubled and there we go all right so you can also chain with other methods it doesn’t just have to be map so let’s say that we want to first of all filter out and just get the even numbers then we want to double those even numbers so let’s say chaining multiple or chaining different methods so let’s say we still have we still have this numbers right here right this numbers array so that’s what I want to use so I’m going to say const and then even double so first I want to take numbers and I’m going to filter you know what let’s make this 10. so 5 6 7 8 9 10. okay so I’m going to say numbers filter and then for each number I want to remember we’re using filters so we want to say number and then we’re going to use modulus 2 equals zero so that should just filter out and give us the even number so let’s console log even double so right now it’s just going to give us 2 4 6 8 10 but now I want to add on a DOT map so I’m going to put this on a new line get rid of that semicolon and then do a DOT map so I’m chaining these these methods here I’m going to get let’s say number and it’s going to be the result of this this which is going to be an array of you know an array with the even numbers so now I’m going to take those numbers each one and multiply it by two save that now they’ve been doubled and you can do this as much as you want you can have 10 chained methods and they can all be different all right as long as it makes sense so hopefully this is giving you an idea of how these these methods work and there’s there’s a lot more we’re not going to look at all of them right now one more I do want to look at in the next video is reduce all right so now we’re going to look at a method called reduce which is used to reduce your array down to a single value and this can be a little tricky to grasp at least for me it was a little trickier than some of the others but a good use case for this and a good example is a shopping cart where you have you might have an array of products with different prices and you want to reduce that down to a total of the prices for your shopping cart that’s somewhere where you’ll see reduce a lot so if we look at this example here a very simple example there’s three arguments that I want you to understand here so basically reduce takes in a function just like the rest of them and there’s two arguments here previous value and current value so previous value is basically what’s returned from the last iteration or the last function that ran last callback this is also called the accumulator so if you hear accumulator in previous value those are both usually mean the same thing and then the current value is whatever the current element we’re on okay and then you can also pass in as an additional argument here the initial value which is whatever you want the initial previous value to be because obviously your first Loop through you’re not going to have a previous value so you can set that here and in most cases it’s going to be set to zero all right so let’s let’s look at a very similar example and then I’ll show you a like a shopping cart example so let’s say we have an array of just numbers and we’ll just use one to ten okay and then I want to get the sum of all of these numbers so I’m going to create a variable called sum and let’s use reduce on the numbers array and like I said it’s going to take in a function just like the rest of these array methods and actually Let’s do let’s do a long version of the function first just to kind of give you a better idea of what’s going on so the function will take in the either the previous value or accumulator I usually use accumulator and then the current value all right and then to set the initial value which isn’t actually required but if you want to set that you can add it after the the curly braces here and let’s say zero set to set that to zero oops and then in here what I want to do is return the accumulator so every time this runs I’m going to take the accumulator or the previous value and add it to the current value and that should in the end give us a sum of all the numbers so let’s come down here and console log sum and let’s go to our console and you see we get 55. so basically it started at zero because that’s what we set here then it went through ran a function for each element took the previous value so for instance when it was on 2 it took one and then added the current value so it added two then it the function ran again for the next element and it took 3 and added the previous item or value which is two and I kept doing that until we’re done with the array all right and then of course you can shorten it up and we could say const sum equals numbers Dot numbers dot reduce and pass in here an arrow function and you could shorten it up to like ACC is is commonly used and then c u r r c u r for current value and then we could just say we want the accumulator plus the current value and then for the initial value we’ll pass in zero and let’s just change the variable name to sum2 and we’ll console log sum2 and we should get the same thing now if I take this initial value and I set that to let’s say 10 and then I save that and run it you’ll see we get 65 and the reason for that is because now we’re starting at 10 okay before we do anything we’re starting at 10 and that’s what this accumulator is going to be on the first run through so now we’re going to get 10 more than than we normally would okay so I just want you to understand what these these arguments are now to make this even a little more clear I’m going to do this with a for Loop so we’ll say using a for Loop because there’s so many different ways to do the same thing and if you were to use a for Loop instead of reduce that’s not wrong at all it’s just a little longer so I’ll even put this into a function we’ll use a function expression so I’ll say const sum 3 and then set that to to a function so I’m going to initialize the accumulator so we’ll initialize that at zero and then we’ll do a for Loop and I’m actually going to use a 4 of since we’re going through an array so we can say const and we can call this number or we can even call it Cur like like we did above of numbers because that’s the name of the array and then all we have to do is set the accumulator equal to the accumulator Plus the current value okay now an easier way to do this or a shorter way to do this is to use the plus equals syntax we can just do that all right and then outside of the for Loop we’ll go ahead and return whatever the accumulator is and now if I come down here and I run a console log of sum 3 uh whoops this is a function I need to make sure we add the parentheses and now you can see we get 55. okay and there’s just so many ways to do this you could even do this same kind of thing within a four each so hopefully that kind of puts us into perspective a little bit now a more realistic example would to be to have a shopping cart so let’s do that I’ll say we have this cart which is an array of products we’ll say let’s give it an ID we’ll say ID and then name product one and then a price price will say 130 and then let’s say we have three products so this will be two three and product two product three and then the pricing let’s do 150 and then 175. all right so if you want to pause the video and try to get use reduced to get the total of these prices then you can do that now so we’re going to go ahead and create a variable of total and set that to cart dot reduce and we could we could either pass in a short Arrow function or we could do the long way which I’m going to do here and this is going to take in the accumulator and it’s going to take in the current value now instead of using like Cur or current value I’m just going to put in product because that’s that’s what it is right where We’re looping through these products and each value is going to be a product so that makes more sense to me and then we’re going to just return from here the accumulator plus now if I just do product right because that’s what we did up here we just plus the current value it’s not going to work here because these are objects these the the actual elements that We’re looping through and running the function on were the numbers we were adding in this case it’s a property of price so you want to make sure that here you add dot price all right and then for the initial value we’ll set that to zero and now if I go ahead and console log the total we get 455. okay if I add let’s say let’s make this 200 and save now it’s 480. so this is something that’s extremely common with things like shopping carts all right so that’s reduced now there there are other high order array methods and I want to get to those but I know that some of you are dying to just start to work with the Dom and actually put things in the browser and work with events and stuff so we’ll get to some of the other ones later when we can actually Implement Dom elements but before we do that I just want to give you a couple challenges in the next video okay so now we’re going to do a couple challenges with array methods and these aren’t too difficult if you watch the past three or four videos then you should be able to to get this at least one of them so the first challenge is to you can see we have an array of people has a first name last name email phone and age so the instruction is to take the people array and create an array called young people that stores objects with only the a name and email property of all the people that are under 25 or 25 and under and the name property should have their first and last name so basically we need to convert this into an array that has just a single name property with both their first and last name and only the people that are on over what is it no 25 and under okay and you should just have a name and email property and again the name should have both the first and last name so that’s what we want to get from this array is the the expected result so if we console log young people then we’re only going to get these three because they’re all 25 or under you can see we have a name property all right so if you want to try that out go ahead and pause the video and you can do it on your own all right so I’m going to copy this array so we can use this and then let’s come over here and let’s paste that in all right so we need to first of all I mean you can do this in different in a different order and you can use different methods I’m going to go ahead and filter out the the young people or I should say filter out the older people so that I only have young people so let’s say const young people and we’re going to set that to the people array we want to filter through that right so in filter let’s pass in a function and we’ll say for each person we want to return only if the person is less than or equal to 25 all right so we can go ahead and console log that let’s say Young people and save that and I get nothing let’s see what did I do wrong here people.filter person we’re going to return if they’re less than oh I forgot the age so I’m saying just person which is the entire object of course we want the age and if we check it out we get Jane Sarah and Jose that looks correct so Bob is 45 Jane is 25 so she’s included John is 30. he’s not included so it looks like we haven’t filtered down now we still have all the properties we want to narrow this down to only have a single name property with both first and last name and email so so what I’m going to do is is chain on a map method here so let’s say map and in here we’re going to pass in the person and remember what I’m passing in here is going to be the return from this so it’ll be the filtered persons that I’m accessing here and then I just want to basically rearrange it to just have the name and email so I could do a couple things I could do this and then and then use return return the object or since I’m just returning a straight object I could put parentheses here and use my curly braces and do it this way and say name and we’re going to set that to the person Dot first name and then I’ll just concatenate you can use template strings if you want but I’m just going to concatenate a space and then add on the person dot last name and we also want the email so we’ll set email to person Dot email so we’ll save that again and let’s see what we get so now we have an array and it only has the name and email and the name has the first and last name all right so that’s the first challenge so the Second Challenge is to add all the positive numbers in the array so here we have an array called numbers it has both positive and negative we want to be able to console log our our variable that has you know our solution and we should get 79 so 50 plus 20 plus 2 plus 7. all right so you don’t want to add the negative numbers so again if you want to pause the video and go for it then you can do that now so I’m just going to add comment here say this is challenge one and then let’s go down here and here is a challenge two so we have our numbers let’s actually just copy let’s grab this okay we’ll paste that in there all right so we want to be able to add we want to add all these numbers so let’s create a variable here called positive sum and again we’re going to be filtering out some stuff here so let’s say numbers and I’m going to go on to the next line and filter and what we want to filter let’s pass in our function and say for each number we want to let’s say we’re going to say if the number is if the number is greater than zero so that’s the truth test right if it’s if the number is greater than zero then it’s going to get put into the array now if we console log this positive sum I get 250 27 so right now we just have an array of the positive numbers now we need to get the sum of those prettier fix this for me I didn’t want it fixed but it’s all right now I’m going to come down here and I’m going to use reduce to add them together so remember reduce is going to take in the accumulator or the initial value and then the current value and then oops and then we want to run our function which is just going to take the accumulator and add on the current value and we’ll pass in zero as the initial value so now I’ll save that and there we go we get the single value of 79. all right for the next one we’re going to create so we have this this words array coder programmer developer all lowercase and now we want to create a new array called capitalized words with the words from this array but have the first letter capitalize so this is the result that we should get okay so shouldn’t be too difficult let’s go ahead and say challenge three and we want the words so let’s create that array first so the words are coder and programmer and these are all lower case and then developer okay so now I’m going to create a new variable just call it c word so capitalize words we want to set that to the original words array and we want to map through because that’s what we want to do is we want to map through and manipulate this and and create a new array with the capitalized words so this takes in a function I’ll use curly braces here and pass in word because for each word we want to then return and this is similar to a challenge we had I think in the first section where I had you uppercase the first letter of of a single word now we’re doing it in Array but what we did then was we used two uppercase now if I were to add to uppercase to the whole word then and then let’s return this I’m sorry console log this c words and save then all the letters are uppercase which we don’t want we just want the first one uppercase so there’s a few ways we can do this we could use the Char um uh method here or we could just use the index because even though it’s a string we can still use the index to get a specific character and we want to get the first character so if I save that now you’ll see that we’re just getting the first character in its uppercase now we just want to add on concatenate on the rest of the word and we can do that with slice remember if we take the word and we we use dot slice we can return a specific part of the word and this goes by index so I’m just going to put a 1 in here not a 2 a 1 and that will get basically from the one index which is the second starts at zero and it will get that over okay from there on or you could pass in a second argument to where you want to go which would be the entire length of the word so I could say word dot length as the second argument so if we save that now you’ll see we get Coda Pro grammar and developer and we have the first word uppercased all right so that’s it in the next section we’re finally going to get into working with the document object model and actually doing stuff within the body of the web page I know we’ve been doing a ton of console stuff but I think that this what we’ve been doing is really really important for you to understand before we move on to button events and doing you know moving things around in the browser or whatever I think the the fundamentals including iteration and control structures and data types that’s all really really important for you to understand all right so let’s move on to the next section all right guys so in this section we’re going to start to look at the Dom or the document object model and I’m sure that a lot of you have been waiting for this section many of you may have even started the course here I just want to mention that before you jump into the Dom you should have a good understanding of the fundamentals so things we’ve talked about like data types functions flow control loops even array methods I would suggest that you have a basic understanding of that stuff first now I’ll talk more about what the Dom is in the next video but it’s essentially an interface that allows us to interact with page elements dynamically from a language like JavaScript and in this section we’re going to look at things like the properties and methods available on the document object including methods to select elements we’re going to look at how to Traverse the Dom and navigate it so that we can change and add and remove elements from the page dynamically also change Styles and attributes so there’s a lot of different methods and functions that you’re going to learn so I would suggest following along and keeping the sandbox handy so that you can reference it at any time now after we learn how to manipulate the Dom in the next section we’re going to start to get into events so that we can have even more Dynamic functionality alright so let’s get started okay so now we’re going to jump into the document object model and we’re going to spend half the half this video in some slides and trying to give you like a visualization of the Dom and then I want to jump into some code and we’ll look at the the window object which has a child object called the document object now as far as what the Dom is it is essentially a programming interface for web or HTML elements we already know we can display the content of web pages using HTML tags with text and we can style it using CSS you guys should definitely know that at this point and the Dom is is the structure of the web page that we can interact with we can interface with using JavaScript and you can use other languages as well but for the most part you’re going to be using JavaScript and it generally includes all the HTML tags so you have access to those attributes the text between Queen tags those are called text nodes and when you visualize the Dom you usually visualize it as like a tree structure similar to what you see here on the right and what you see on the right is a tree structure of this web page here which is very simple so we just have our HTML tags head and body tags we have a div an H1 a paragraph so over here I’m going to talk about window and document in a few minutes so let’s just look at HTML now this HTML element here represents this HTML tag in our page structure okay and we will be able to access that through the document object and in that HTML tag we have two children or child tags or elements we have the head and then we have the body now in the head we have another title element and in that title element is a text node so a lot of people when they start out a lot of them think that the Dom just it just refers to the tags right the elements well it also refers to text nodes it also refers to attributes so you can see in the head tag we have a meta tag and that has a character set a Char set attribute on it which we can easily access and and do things to add to remove or whatever on the bot in the body we have a div and that div has an attribute on it of ID and then in that in the div with the ID of main we have an H1 that H1 has both an attribute has a class on it and it has a text node in it all right and then the paragraph has a text node in it as well so when you look at HTML structure you should be able to kind of picture this type of thing in your head when you’re dealing with the Dom all right now I want to just jump into vs code now and just kind of look at some of this real quick so in the console I’ve already showed you this if we type in window it’s going to show us that the window object which is the the topmost or the global object in the browser that has a ton of stuff on it including the document object and we can of course access that from within our code as well all right that’s going to give us the same thing and in that window object is the document object so right here and that has a bunch of properties and a bunch of helpful methods that we can use as well so we could do a console log window dot document and I’m just going to comment this out so now you’ll see document and since we did a console log to the document it’s going to just show us the element if we want to see like the properties and methods and stuff then we can do a console.dir and now if we take a look you can see all this stuff here and I’m going to go over a lot of the different properties in the next video now I’m just going to show you a couple things and we’re going to touch on all this stuff much more later on but let’s just do a console log here and we’ll say document now we don’t have to prefix it with window you can because it is on the window object but since window is the top level object you don’t need to prefix this stuff with window in fact you’ll very rarely see window dot document so as you can see over here there’s a body property here and that that references the body element so if I say document.body and save that it’s going to show me the actual element okay so you see the body element you can see the H1 and the script tag some of this stuff is injected by live server but we can see everything in the body right and then there’s properties we can use on this like let’s say we just want the HTML in the body we could use inner HTML save that and now you can see we have an H1 and our script tag and if we look at the HTML page that’s exactly what’s there if we wanted to get let’s say just the text we could use in our text save that and we just get Dom intro all right if I were to add something else in here and just put a paragraph with hello just the text is going to show here if I go back to using in our HTML it’s going to show the paragraph as well all right now typically you don’t access elements with direct properties like this because there’s methods like like get element by D and query selector that I’m going to show you very soon that helps you target what you want much more easily I but I do want to just show you some of the I guess the the more difficult ways of doing it first so let’s say we want to get all the links on a page all right and I shouldn’t say more difficult but but using properties rather than using the the methods so let’s create a link here and I’ll just have it go to my site travestymedia.com and say Traverse media for the text all right and then let’s say I wanted to access all the links I could say console log and then document and if we look over here in the properties there should be a link so you can see there’s images to access all the images and then you also have links now since there’s more than one link on the page what this gives us is something called an HTML collection which is very similar to an array you can access each link by index just like you could in Array so let’s say document.links and we’ll console log that in fact let’s comment out this stuff here so as you can see I get an HTML collection and there’s a single Link in there it has an index of zero so if I want to access that I can simply put brackets just like I would with an array and then put the zero and there it shows me the link okay and if there were if there was another link I could use one as the index there’s not so it’s going to just be undefined now this for instance this document.body this is not read only I can change that from here I could say document.body equals or actually let’s say document.body dot in our HTML equals and then we’ll just put an H1 in here and we’ll say hello world all right so if I go ahead and save that it’s going to replace everything that’s in the body with just this H1 even if we had you know a ton of content on the page if I set the body in our HTML to this H1 it just replaces it now I’m going to show you all kinds of methods to insert things where you want but this is just saying well I just want the entire page to show this H1 which is something you’re not going to do now there’s also methods I’m just going to comment that out there’s also methods on the document on the document object so one of them which you don’t see very much is right so right will actually take whatever you put in here and write it to the browser so if I say hello from JS and I save it gets added now the reason you don’t see this used very much is because there’s no targeting it just basically puts it at the whatever at the end of the file and it’s not it’s just not very helpful but this is a method right it’s a function now there there’s also methods to select certain elements in the Dom and those are very very helpful and we’ll be going over those you know in depth but just to give you an idea let’s go to the HTML and let’s wrap I’m going to wrap all this the H1 and the link with an ID of main okay so I have this div with the ID of Main and I’m going to move the H1 and the link inside of that and let’s say I want to select that Main that main ID so I’m going to just console.log document Dot and then the method I want to use is get element by ID okay so we’ll say get element by D and in here is going to be the ID I want to grab which is main if I save that and you see it grabs that div with the ID of main now I can do what I want with that I could say document Dot get element by D main I could also put this into a variable so for instance const main equals that and then I could say main dot inner HTML equals and then we’ll put an H1 and we’ll say hello from Main okay save that and it’s going to replace everything within that that div with the ID of main with this H1 okay just like I replaced it up here I replace the body this is just replacing this specific element okay and there’s there’s even better selectors like query selector where you can select anything you want so for example if I wanted to select just the H1 I could say document dot query and don’t worry we’re going to go over this much much more in depth so I could say query selector uh and let’s say I want the ID of main so I would use the number sign here because you can choose classes or or just straight elements whatever and then I want the H1 so it’s basically like if you were styling this with CSS you can put any selector in here and let’s say I want to take the inner we’ll do the inner text of that H1 and let’s set it to hello save that and now just the H1 gets changed so this is just a very very high level example of some of the things that we can do all right so in the next video I want to look more at some of the properties on this document object all right so in the last video we looked at the document object model and what that is we looked at the actual document object that we have access to within the window object and some of its properties and some of the methods we can use so I want to take a look at some more properties that’s on that object that you have accessible to you that you can you can access you can also use to overwrite and you know add things through JavaScript so a lot of these you’re not really going to use because instead of selecting them the elements with these properties you’re going to use methods like get element by D and query selector but I do want you to at least know that they exist all right so you’ll notice that we actually have some life in the browser finally so this is a UI for the shopping list application that we’re going to build in a little bit and it’s not functioning you’ll see I cannot add anything I can’t delete anything that’s because there’s no JavaScript at all it’s just HTML and CSS and you’ll have this in the sandbox you’ll also have it in you should have it in this the current video module that you’re watching all right and just to take a quick look at the HTML we’re just bringing in font awesome which is a library to use icons like this right here I believe is actually no that’s not how to font awesome the think just the delete buttons are here but yeah so we’re just bringing that in the bringing the CDN and then we’re linking in our style sheet so this is just custom CSS so very simple we’re not using like Tailwind or any CSS framework and then we have our header our container with our header just has this little image and and heading and then the form here with the input to add an item the button to add an item then we have a filter input as well so we’ll be able to filter these items down then we have the unordered list which is the item list and then we have the clear all button so that’s pretty much it and then we’re linking in a script JS which is completely empty That’s why nothing works okay and and a little later on we’ll create this whole application and get it functioning but I want to use it just as an example UI for the next few videos so that I can show you how to manipulate the Dom and you know access certain elements change things and so on so again I want to look at some of the properties on the document object so I’m going to just initialize a variable here called output so that I can console logs different things and let’s open up our console over here so the first property I’m going to show you is actually deprecated but I still think you should know it and that’s document.all so I want to set output to that so we can log it now you’ll see it actually has a strike through in vs code because it says it is deprecated but if we look over here what it gives us is an HTML all collection so this is similar to an array and you can see it has brackets and it’s basically an array or a collection of all of the different parts of the this page the Dom for this page so HTML tags a script tag head tag everything in here the form the inputs everything is going to be in this HTML all collection and we can even access axis Elements by index so if I do 10 that gives us the body if I do 11 that gives us the container so you can access items or elements like this but this is not like the way you want to do it this is not very convenient and this is the reason I wanted to to teach you like what arrays are and how to use them and stuff because if if you didn’t know what an array is you wouldn’t understand an index or what this is right so it’s important to learn the basics now you can also use like the length property just like you can on a regular array so you can see there’s 38 items in there but it is deprecated I wouldn’t suggest using it but I want you to know what it is just in case you run into it now we also have if you want to get everything that’s in the HTML element or tag you can use document element and that will just give us the HTML tag and then everything in it head body and so on then we can also access just the head or just the body so if we say document dot head and we save that that gives us the head we can do the body I showed you that in the last video as well now if you want to get the children in the head or the body so if you want to get the children in a collection you can it’s actually do that so you can just do dot children and now what we have here is a collection of everything that’s in the head the script tag meta tag link tag we can do the same with the body so if I do that that gives us everything that’s in directly in the body that’s why there’s only a single div here because if we look there’s a this div with the class of container everything else all the other HTML is inside of that so it’s only going to give you the the parent I should say the direct child of the body if I were to put an H1 in here and save that that H1 will get added to this collection because it’s at the top level right where container is so that is dot children which you can use on the header body now some other properties we can get are the the doctype so let’s say output equals document dot doctype if for some reason you need to get that we also have the domain domain I believe is deprecated as well but as you can see we can get the domain which for me is my Local Host we can get the URL the full URL as well so that’s going to be the domain plus any page that we’re on we can get the character set so character set which is utf-8 so just some things that you can get for your application if you need them the content type so we can say document dot content type which is going to be Text slash HTML now I showed you that we could get links as an HTML collection in the last video and I’ll go over that again in a minute but we can also do that with forms so I could say document dot forms and save that you see that gives me an HTML collection of the forms if I want to access a specific form I could use an index because again an HTML collection it works like an array as far as indexes go so you’ll see I get my my item form here now I can also get specific attributes on elements as well so let’s say I want to get the ID I can say dot ID and you’ll see I get item form okay I could get the method of the form so we can say method save that and it’s going to be get because we don’t have a method described here but a form is always going to it’s always it’s always going to be get as the method unless you set it specifically like if I set it to post so if I say method post and save then it’s going to be post and we’ll get into what that means later on there’s also no action which is where it submits to if there isn’t an action it’s going to submit to that page but I could get the action with DOT action and it should just be the same page so the page that I’m on now if I wanted to change the ID of the form I could do that by saying document dot forms and grab the first form in the document and take the ID and set it to let’s say new Dash ID right so if I save that now and I come over let’s go to the elements Tab and take a look at the form I’m going to close that up and you’ll see form has an ID of new ID so I set that from my JavaScript all right um I’m just going to comment that out though now I could do the same thing with links as I showed you in the last video so I could say document dot links which do I even have any links in here let’s go back to the console here yeah so it’s just an empty collection because I don’t have any links if I did if I put like let’s say https google.com and I’m going to get rid of this after but just to show you if I have a link then that’s going to get added to the collection and then I can access the first and only link with the index of zero and if I want to access just the just the link the href I can use the href property so I’ll say dot href all right if I wanted to set an ID onto this link I could say dot ID and set that to let’s say Google Dash link and if we go back into elements and we look at the link which is let’s see where is it um I think it’s in here yeah so ID Google link I could even change the href so let’s copy that down and set that to https facebook.com and save and now if we look again at the link right here you’ll see the ahref is now Facebook okay and then for classes like um for those CSS classes you could change now you can’t do this you can’t say dot class but you can do class name and I’ll set it to I don’t know Google class and save and now you’ll see we have a class of Google class and then if we want to access all of the classes we can get a collection of those with class list so let’s say dot class list and I’m not going to set this I just want to log it so we’ll save that and go to our console and you’ll see that now we have it’s actually called a Dom token list so any classes on that element will be in this list all right now we can do the same with Let’s see we did forms links we can also do images so let’s say output equals document dot images which will give us an HTML collection if I can spell this right document so that gives us an HTML collection of images let’s get the first image so this index of zero and that’s going to be this right here this note PNG which is the first and and only image if I wanted to get the source of that image we could use the source property all right so I just want you guys to know these these different properties that we can use to access these elements now the this is not the best way to do this if you want to access a form if you want to select it for something you don’t really want to do this or this for links or this for images but I want you to know that this does exist because you might run into it and there might be some reason why you do have to use it now I’m just going to get rid of this Google link it’s going to throw an error because it’s looking for links and I don’t have any so I’m just going to comment this block of code out and then the last thing I want to mention is that what we’re getting back when we do this document forms document images is an HTML collection which is array like we can access the specific uh forms for instance using an index just like an array but if we try to use a for each on it it’s not going to work so let’s actually try that out if we say document let’s use form so we’ll say document.forms.4h you guys should know this we went over this in the last section and this takes in a function we’ll say for each form then we just want to console.log the form right now if I save that it’s going to say that for each or forms.4h is not a function okay because 4H is not a function for what we have here which is an HTML collection okay later on when we use Query selector that actually gives us something called the node list which is different than an HTML collection and we can use for each on that but for an HTML collection if you do want to use four each you would have to first convert it to an array and you can do that with the array from method that we looked at a while back so I could say const forms right create a variable called forms and set it to array capital a DOT from and then pass in our document dot forms HTML collection and then I should be able to take that forms array and then Loop through it and now you can see it’s outputting this uh this form here okay because we only have one form if we had more it would show them here because it’s looping through and logging it okay so I just want you to understand an HTML collection is array like but it’s not actually an array and this is how you can turn it into one now in the next video we’re going to start to look at methods that we can use to to more easily select elements from the Dom all right guys so in the last video we looked at many of the properties available on the document object including properties that allowed us to select elements from the Dom in the form of HTML collections now in this video we’re going to look at a much more common and practical way to select elements and the methods that we’re going to use here are to select single elements on the page so if you want to get let’s say all of the paragraphs on the page you wouldn’t use these methods we’re going to look at those in the next video methods to select multiple elements for this is like if I wanted to select this particular H1 or this particular input then we would use these methods all right so the first one has been around for a while and it’s going to be document.getelement by ID so basically it does just that it’ll allow us to get any element in the Dom by its ID so if we look at let’s see if we look at the elements tab here and in the dev tools you’ll see that this H1 has an ID of app title so I want to get that let’s go ahead and we’ll do a console log of it first so document dot get element by ID and it has an ID of app dash title so if I were to log that in the console we’re going to see that H1 now there’s going to be cases where you want to get a specific attribute so what we could do is there are properties available such as ID and there is an ID on this element so I could just add on dot ID now that doesn’t work for every single attribute for instance if I do dot class I get undefined and I know there isn’t actually a class on here but I’ll show you real quick if I were to add a class onto this H1 of say hello if I do that we still get undefined because class is not a property now there is a class name property and you’ll see that does get it but there’s no that’s not always going to be the case get rid of that so what you can do is use a method called get attribute so I’m going to copy this down and instead of this dot class name I’m going to say dot get attribute and that’s a method so it takes parentheses and then we can pass in whatever attribute we want I’ll pass in ID and you’ll see now we get app title now there’s going to be cases where you want to set attributes not just get them so there’s a few ways to do that so one is to grab the element so let’s say app dash title and let’s say I wanted to change the ID I could say dot ID and set that to let’s say new Dash ID and if we look at the element now it has an ID of new ID now if I keep this here and then I try to select by ID and I use app title again it’s not going to work because that’s been changed so let’s change this to something else we’ll add a title attribute and we’ll just say shopping list and a title will typically you know if you hover over this it’ll whatever the title is will show all right now like I said there’s not always a property for that that we can use so there’s also a set attribute method so let’s copy this down and what we’ll do is get rid of this and we just want to do dot set attribute and that’s going to take in two things the first is going to be the attribute you want to set let’s just use class and then what you want to set it to so I’ll say title and if we look here you see now class is equal to title I could have said dot class name equals title so there’s many ways to do the same thing but I just want to show you that there’s both a get attribute and set attribute and we’ll talk more about this later as well now there’s going to be times where you don’t want to type all this out like if you have to use this selector more than once you might want to put it into a variable so we can do that by just setting a variable and then setting this to get element by D and app dash title so now if I were to console log title then that’s going to give us the element now I know that this video is showing you these different selectors and we’ve only looked at get element by D we’re going to look at query selector next but I want to show you some of the things that we can do when we bring these in when we when we grab an element from the Dom all right and and we’ll go into some of this stuff more in depth later on but one of the things you’ll do is either you either want to get or change or add the content that’s within that element right so what we could do is say well it’s console log first title which is our element our title element and we could do text content which is a property that will get the content inside of it in this case you can see shopping list okay now we can also change it as well by saying title dot text content and setting that to something else let’s just say hello world save that now you see we’ve changed change that element’s text there also is intertext so if I say inner text like that and we’ll just set it to hello again that’ll basically do the same thing there are some differences between these two but I’m not going to get into that right now you’ll most commonly see in our text at least in my experience now if you want to use HTML tags then there’s a property called inner HTML so you’ll use this a lot with vanilla JavaScript but with this I could set it to let’s add some strong tags and we’ll just set it back to shopping list so let’s say shopping list let’s close our strong tag and save that and now you can see now it’s strong or bold so another thing we can do is change Styles so we can actually edit our CSS from here so for example if I say title Dot and then we use style and then whatever CSS property we want so for instance color I’m going to set that to red and you’ll see I can change that color to Red now it’s important to know that if you’re if your style has if your property has two words like let’s say background color in CSS you would do this right bat Dash color background Dash color you can’t have a hyphen here so in JavaScript what you do is just use camel case like that and then let’s just set that to we’ll say black okay and then maybe you want to add some padding so we could change the property here to padding and set that to let’s say 10 pixels right and then we’ll just do a border radius it’s a border radius so it’s two words so it’s camel case now you might be saying why the hell would I want to use JavaScript to edit Styles well you wouldn’t do it like this just to edit a static page styles on a static page when you want to have your your interface be dynamic that’s when you you do this type of thing so for example if you want to have a pop-up if I were to hit this button and have something pop on the screen a modal you would be changing your yours or adding CSS to your JavaScript okay or you would just change classes you would change a class to like show or hidden or whatever and we’ll get into that later but I just want to show you now that you can select elements from the Dom and then you can change things or add or remove whatever you want okay so you have full control of your interface through JavaScript and the Dom so now we’re going to move on to the other selector that you’ll use for for single elements and that is document Dot query selector now this was a game changer when it came out before that if you’re using vanilla JavaScript we had to use get element by D so whatever you selected you had to have an ID on uh and in some cases you didn’t have full control of the HTML so that’s where jQuery came in and gave us a big Advantage because we could select anything we could just select an H1 with no class or attribute we could select by class we could select by anything at all so that’s really what query selector gives us and this came along with the es6 or es2015 update and kind of put jQuery out of business as as like a Dom manipulator so let’s start off by just we’ll do a console log here and let’s say document Dot and then query selector there’s also query selector all which is for multiple elements and we’ll get into that next in the next video but if I if I want to select just by the selector I can do that so H1 and you’ll see it’s showing our H1 along with all the styling and all the stuff we did up here to it now remember this only selects single elements that’s kind of the difference between jQuery and this if I did this with jQuery it would select I believe it would select all H1s I haven’t used it in so long but I believe it would select all of them in this case it’s going to select only the first one if there are multiple on the page all right but usually you’re going to use this to select like a class or something like that something that you know there’s only one of otherwise you’ll use Query selector all so another thing we could select by is ID so we could say app dash title okay so that’s going to log the same thing the H1 with that that ID we can select by class so if I say dot container and we select that you can see that we get the container and you can do all the same stuff with Doc query selector right you can change Styles content and all that we could even do it by attributes so for instance if we want to get the input that has a type of text we could say input and then in Brackets here I could say type equals text actually that takes takes quotes I believe okay and if I go ahead and log that you can see now it’s it’s grabbing this input here now we can even use pseudo selectors so basically anything you can use within CSS so let’s get rid of this and instead I’m going to say an A List item if I do this it’ll just give me the first list item by default let’s say I want the second list item so I could say Li and I could use the pseudo selector of nth Dash child and pass in here two so that should give me the second list item which is orange juice and let’s actually we’ll do the inner text save that and there we go orange juice so you can select and you can Target anything on the page you want so let’s do this let’s take the document query selector and the inner text and let’s put that into a variable so we’ll say const and I’ll call it second item and we’ll set it to that okay so that’ll give us the inner text actually you know what let’s not do the inner text because I just want the element and then let’s set the inner text so we’ll say second item and then dot enter text and let’s set that to let’s say apple juice if I save now we get apple juice okay if I wanted to change the color of it then I could take the second item and change the color I’m sorry we need style so style Dot color and set that to red all right and I would encourage you to maybe you know after this video try and change some things around with what you’ve learned try to change this this interface up maybe change the color of the button change the text of the button things like that now another thing that I want to mention is that you can use you can use these use these methods on other elements other than the document so for example let’s select the entire UL so we’ll say list and then we’ll set this to let’s say document dot query selector and we’re going to select the unordered list okay which is just this right here right apples apple juice Oreos Etc so that gives us the the entire UL if I console log list it gives us the UL now if I want to select something in that list like say the first item we can use Query selector on list okay it doesn’t have to be on the the document so let’s take list and then let’s say query selector and let’s say we want to get we’ll just get the first list item and yeah we’ll just do that and then let’s actually put that into a variable we’ll just call it uh we’ll call it first item so first item equals that and then we’ll take first item and let’s change the we’ll just change the color we’ll say dot style dot color and set that to Blue save and ioc apples is now blue so you can use Query selector on any element it doesn’t have to be just on the document all right now in the next video like I said we’re going to get into selecting multiple items all right so in the last video we looked at get element by D and we looked at query selector which are the two methods you can use to select single elements now if you want to select multiple elements like let’s say all of these list items then there’s some other methods you can use now query selector all is the method that you’ll use probably a hundred percent of the time there’s some older ones like get Elements by class name and get Elements by tag name which I will show you just so you know but you’re probably just going to use Query selector all so you can get by just using this and query selector for multiple elements now as far as what this gives us let’s go ahead and I’m just gonna I’m gonna create a variable here called list items and what I want to put in here is all of these these Li tags all of these list items if I go to my elements tab here and click on that you’ll see that we have these these Li tags and they have a class of item I could use that as well for my selector but let’s say we want this to equal document dot query selector all and I can put Li in here I could also like I said I could do class item and that will select all of those let’s leave it at that because if you were to add other allies on the page somewhere else those would also get included if you just use Li now if I console log list items I just want to show you what that gives us so let’s go to our console and what what it gives us is a node list and a node list is an array-like structure much like an HTML collection which we saw in the past in fact the older methods I’m going to show you do return an HTML collection as opposed to a node list now there are some differences one key difference is you can use high order array methods on a node list you can’t do it with an HTML collection with an HTML collection you would have to first convert it to an array and I’ll show you a for each Loop in a minute but I want to show you you can also get if you want an individual item just like an array you can use the bracket syntax if I put a 1 in here that gives me the the second element let’s say I just want the text I could do let’s say inner tab okay and that gives me orange juice because it’s zero one two three and I’m getting the one the index of one getting the inner text you can access individual elements like that like an array now if I were to let’s say I want to make all the the I want to make the color of these red so I couldn’t just do list items.style dot color and set that to red if I try that that’s not going to work because I’m trying to run I’m trying to access Style on a node list okay style is is for a specific element now I could do this I could say one and change that’ll change just that but what I would do if I wanted to change all of them is is a for each Loop right so I could say list items dot for each and in here we’ll say for each item and then we’ll take the that specific item and let’s take the style set the color to Red save that and now they’re all red okay now this is different from jQuery for those of you that that have worked with jQuery because with jQuery you could in fact take the you know list items variable and do dot style color and they would all turn red but it’s a little different with vanilla JavaScript and you can do whatever you want in here like we could say if let’s say if item and remember we can access the index so I could actually do this because we already know how four each works we can pass in an index and we’ll say if the index is equal to one then let’s take the item and let’s remove it so we’ll say dot remove and we’ll get into methods like this later but now you can see that that has been removed now let’s say we wanted to change the the text of the first one from apples to oranges so we could do if and then say if the index is equal to zero then let’s take this particular item and change the inner text we’ll change it to oranges save that now notice the text does change but the delete button is also gone whenever you’re working with elements you have to know exactly what you’re working with if we look at a list item here it doesn’t only include the text it also includes a delete button so you have to take that into an account into account so what we could do is just take everything that’s in the list item and copy it and then here this there is HTML in this so we would say enter HTML and then I’ll use a template string just so it’s easier so use some backticks here and paste this in and then change apples two oranges save and now we have oranges and the delete button is also there so you see a lot of stuff like this template strings um within your in vanilla JavaScript all right now I want to show you some of the other methods that we can use that you probably won’t but I do just want to show them to you so I’m going to comment this out just so we have our original our original list back and then let’s say we want to select all these with the get Elements by class name so I’m going to say cons list items we’ll call it list items two and say document Dot and then it’s get Elements by class name okay and then we know that they all have a class of item and this is kind of restrictive because you can only do classes and you don’t want the dot actually because it’s always going to be a class just like with get element by D you don’t put the the number sign now if I console log list items two we get an HTML collection as opposed to a node list okay we can still access individual items like like we would with an array like if I put a 2 here and save actually let’s do two and then Dot in our text and we get Oreos okay so you can use you can pass in an index like this but if I were to do a four each so let’s say list items two dot four each say for each item then we’re going to just let’s just do a console log of that item and the enter text save that and it says for each is not a function because it’s not a function for this list items two which is an array I’m sorry an HTML collection now what we could do is use array Dot from to convert it to an array so I could say const list items let’s just call it list items array and then set it to array Dot from and then pass in our list items two which is an HTML collection and then if we run the four each on list items array then we’re going to see that that works all right so just keep that in mind if you have an HTML collection and you want to use for each or any other method you want to First convert it to an array now the um and then the last one I want to show you is similar to this but it’s called get Elements by tag name so I’ll call this one list item three and let’s say get Elements by tag name and then you would put in the tag like Li list item so if I console log list items three again it’s an HTML collection so if you wanted to use a four each you would have to first turn it into an array but you can access specific things like let’s say we wanted the first item that gives us the first item if we want to get the inner text we get apples okay and I’m not going to do much more with these because I’m pretty sure that this is the only time we’re using these in the course okay you want to stick with query selector all for most cases so you can get by with just using query selector and query selector all all right so in the last few videos we looked at how to select elements from the Dom and do whatever we want with them now in this video I want to start to look at the relationships between element nodes okay everything in the Dom is a node and there’s other types of nodes like text node comments nodes we’re going to talk about those in the next video because there’s certain properties if you want to work with those types of nodes in this video we’re specifically going to look at element nodes okay so any HTML tag on the page is an element and I also want you to just be familiar with relationships which you should you should be if you know HTML if we look at this basically it’s pretty simple to tell that this div is a parent of these three divs inside of it and I even gave them the class names of parent and child and then any div that is on the same level such as these three children are siblings right so these are sibling nodes or sibling elements and I didn’t want to use the the shopping list UI just because I want something very very simple so that I can explain these methods and and show you how to use them I’m sorry not methods these are actually properties and the properties I’m talking about are these ones here okay so we’re going to look at all these so we have our parent element which we just saw it was a div with the class of parent and then we have our three child elements and there’s different properties for us to basically Traverse the Dom move up and down so we have we have a property called parent element which does just that we have a first element child a last element child next element sibling previous element sibling and then we also have a property of children which gives us I believe it’s a node list of all the children alright so let’s start to look at this in our code so I’m going to just close that up and I have this open I’m going to open up my script.js here which is completely empty and we’re going to start to look at some of these so what we’re doing here is still just selecting stuff from the Dom but in a way where we do we’re not directly selecting it we’re using elements we’ve already selected we’re using properties on those to kind of navigate and Traverse to the children the parent the siblings Etc so the first thing I want to show you is how we can get child elements from the parent so let’s create a variable here I guess we’ll we can call it parent and let’s say document Dot and then query selector and I want to get the div with the class of parent okay so that gives me if I console log parent gives me that div all right now I just want to create an output variable so let’s say output just because I’m going to be console logging quite a few things so we can just then set it to Output all right and what I want to show you is how to get the the children property so if we look at this diagram here there’s this children property that gives us an HTML collection of all the children so let’s say output and set that to parent and then children now this is a property or an attribute it’s not a method if I put parentheses here it’s going to tell me that children is not a function because it’s not it’s a property and what it gives me is an HTML collection which is an array-like structure of all the divs in here all the child divs now since this is an array-like structure I can access each individual element here with an index so I put if I put a 1 in here I’m going to get child 2 right because it’s zero base so child two would be the one index and I just want to show you if I instead of logging this if I do a console dir it’ll show me like all the properties and methods that I can use on this so we can access like the ID with DOT ID the class list um even the children of this we can access just all this stuff here so just to give you kind of an example let’s put this back to console.log and let’s uh let’s get the inner text save that we get child two right if I do let’s say class name I get child because remember it has a class of child we could even do like the node name which will give us a div because that’s what this is if I take the second one here and change it to An Li then node name is going to be Li all right so we can treat it just like we could treat a directly selected element now I can change things as well so if I want to grab let’s say parent Dot children and then one and let’s set um we’ll say text not text inner text or text content whichever one let’s set that to I’ll just uh we’ll say child and then we’ll spell out the word two so that should replace the child number two and I could also add styles to this so I could say one dot style Dot color and set that to Red so we could do that as well now in addition to the children HTML collection there’s also two other properties that we can use on our parent and that is first element child and last element child now there is just a first child that’s not what you want because that isn’t just element nodes that’s other nodes as well which I’ll talk about in the next video what we want to use is first element child okay so and it’s a property it’s not a method so don’t put uh parentheses and let’s just change this let’s say dot text our inner text and we’ll set that to child one save that and you’ll see it change the first one here and again just to look just to reference this diagram from the parent we called this right here first element child and as you can see there’s also a last element child so if we come back here let’s copy this down let’s change this one to child three and change the property from first element child to last element child and now you can see that that’s been changed so now what I want to show you is how we can get parent elements so get parent elements from a child because if we look at the diagram again it goes the other way as well these child has they have a property of parent element okay and we can also access siblings as well which I’ll get to so let’s go ahead and select from the Dom let’s select it we’ll say child and set that to document Dot and let’s use Query selector and we’re just going to select the first child we’re not going to use Query selector all because I don’t want that I just want to get one of these elements and show you how we can access the parent from it okay so we have the child now let’s set output because I want to show you how we can access let’s say child and then we can use the parent element property so if I save that we output now you’ll see we’re outputting the parent by using the child by using this property on the child now let’s say we wanted to add a border around the parent div from the child so I could say parent element and let’s set dot style dot border and we’ll set that to let’s say one pixel solid and we’ll do Triple C for the color and then let’s say we wanted to add some padding so we’ll say 10 pixels and change this padding and save and now you can see there’s a border around the div with the class of parent and I didn’t apply that to parent directly that I selected I selected a child but then I used the parent element property to access and change the style of the parent so now let’s look at sibling elements so sibling elements oops put two L’s in there all right so let’s grab let’s grab the second item right so I’m going to create a variable called second item and we’re going to use document Dot query selector and remember we can use we can put any selector we want in here so I’m going to say I want the class of child now remember there’s three of those I want the second one so I’m going to use this the CSS pseudo selector of nth Dash child and pass in a 2 here so that will give me the second item all right and just to show you let’s do output set that to second item and save that and you’ll see that now this gives us child two this one right here now if I want to access the next sibling from second item which would be the third one that I could use next sibling right so let’s set output equal to second item and then we’re going to do dot next I’m sorry it’s not next sibling that will do the next node no matter what it is next element sibling will give you the next element sibling so let’s do that now you see it’s we get child three and if I wanted to let’s see let’s just grab this and copy it and we could do something to this like I don’t know let’s set we’ll say style dot color and we’ll set that to Green okay so what I’ve done here is I’ve selected the second item directly using query selector and then I use the next element sibling property to get the next sibling and then I turned it green now we also have previous elements sibling so let’s copy this down and this one let’s say orange and I’m going to change next element sibling to previous element sibling and now you’ll see that first one is now orange because that’s the previous to the second item okay so hopefully this just gives you an idea of how to kind of how to navigate around if you select an item but then you want to get it sibling or its parent or its child there’s different ways to do that now as I said there’s other types of elements I’m sorry other types of nodes other than elements so we’re going to start to look at that in the next video okay now as I mentioned in the last video when it comes to Dom nodes there’s different types and in the last video we strictly worked with element nodes and that’s the most common type of node basically an HTML tag now if we look at this chart here this is actually from w3schools and you can see these are the different types of node types there’s 12 of them now a lot of these you’re not even going to need to know or work with but as you can see the first one here is an element node it represents an element and that’s what we were looking at in the last video and there’s specific properties that we can use that pertain to element nodes now some other types of nodes are attributes okay an attribute like an ID or whatever it might be an attribute on an HTML tag those are attribute nodes we also have text nodes which represent textual content okay so any text written within some HTML tags would be a text node we also have this C data section which represents a c data section in a document which is text that will not be parched by a parser we also have entities and entity references this stuff isn’t really that important to you right now comments so if you have a comment that is also a separate type of node so what I want to do is look at some of these other methods that are available to use with with not just element nodes but other types of nodes as well and this looks pretty similar to what we already saw but these are actually different methods okay same structure we have a parent with three children but we have for instance first child instead of first element child last child instead of last element child parent node instead of parent element node next sibling in previous sibling instead of next element in previous element sibling and there’s also a property it’s kind of cut off here but it’s child nodes instead of children okay so just remember that this works with all nodes while this works with just element nodes which is usually what you’re going to be working with what I’m going to show you here in this video probably you’re probably not going to use too much but I do want to mention it I want this to be a front to back course all right so the only difference between this HTML and the last is I simply have a comment here that says children because I want to show you that a comment is looked at as a specific type of node all right so let’s jump into the JavaScript here and I think the first thing we’ll do is look at the child nodes property just like we had a children property but we want to do that on the parent so let’s go ahead and again create parent document we’re going to query selector and we want to select the class of parent okay and then I’m also going to create a variable called output and then oops and then we’re going to console log that output and let’s just open up our console here okay so right now that’s undefined but I’m going to set output equal to and then take that parent element that we selected and look at not children but child nodes and it’s a property not a method so no parentheses and now you’ll see what we get back is not an HTML collection but a node list and that node list includes all different types of nodes so we have a text node a comment so what I want to do is is go back here and kind of go through and show you what what this pertains to and this goes from the where the parent class as it did with the parent class starts which is right here to where it ends which is right here so all of these nodes are in between that and you might be saying well how I mean where the first one is a text node where is this I don’t see any text well white space actually counts as text so this comment goes on to the next line so this right here is actually that first text node okay if I were to I mean I’m going to have to disable format on Save so if I search for format yeah right here format on Save otherwise it’ll knock it on to the next line but if I take this comment and I put this right here and then get rid of that white space see how right now this is 0 to 8 which is a length of nine because the text node if I save this and look at it now there’s no more text node and it’s a length of eight zero to seven so that text node is gone because that white space is gone if I put that back and I save it then that text node is there again so that’s the first thing next is the comment okay comments of their own nodes if I get rid of this and save then you can see that that com not only is the comment node gone but also is the white space after it okay this right here if I put that back it’s going to go back to a length of 9 and the comment and the white space after it okay this right here then we have our element node which is a div with a child okay div with the class of child then we have our white space which is the text then another div element then another white space with text then another div and then another white space okay so that’s what this is so as you can see this navigating this instead of just the elements like in the last video is much more difficult so you probably won’t be doing this that much unless you specifically need to access text nodes all right let me just put format on Save back on okay so now what I want to look at is we’ll we’ll stick with child nodes just just for a bit just to kind of see how we what we can access here so if I say output and set that to parent dot child nodes and we grab zero that’s going to be that the white space the text node as you can see gives us this text node and we can get all this this stuff from it right like we can get um let’s say text content not with a zero and that just it’s just nothing right if we look at let’s say node name that’s going to be text right so we have we have access to all these properties let’s look at a different one so we’ll copy this down and let’s do three I believe was the first element so if we do three yeah three node name is div if we just look at let’s say the text content we get child one if we look at the we know that that’s the element so we can get the inner HTML which is still child one because there’s no HTML in it if we want the HTML that surrounds it we can use out our HTML which is one t so now it gives us the div with the class of child and child one all right so we’re essentially doing the same thing we just have access to all of the nodes and not just element nodes if I wanted to change let’s say um let’s say dot in our text and I believe this should be the first one so let’s change it to child one spelled out yep so if I if it’s just it’s more difficult to figure out what you need to access because there’s so many of these other types of nodes um what else we could change we could change the color so we could do I think six would be the second one so six dot style dot color equals red or maybe not forget which one was it seven or was it five yeah it was five so that’s the second element all right now in addition to child nodes we also have first child and last child so let’s say output equals parent DOT first child just like we had remember we had first element child but that’s going to give us the text node the white space right if I were to I’m not going to turn off my format on Save again but if I were to put this up here uh not that if I were to put this up here that would get rid of the text node and the comment would be the first one but if I save I have format on save so it’s not going to allow me to do that all right we also have last child which is also a text node um what else let’s see and I could since it’s a text note I could say parent dot last child Dot text content and set that to hello so that’ll replace the text node which was originally white space with hello so now I want to look at parent nodes or getting parent nodes from the child right so what we’ll do is create just like we did in the last video create a child we’ll use document.query selector and we want to select a class of child okay so what we’re doing is selecting this right here now to get its parent node we can use the parent node property so let’s say output equals child dot parent node and that’s going to be the the actual div all right and if we look back at this chart what we’re doing is accessing this parent node now it’s going to be the same as parent element right even though we have these other types of node like text and comment the parent is still going to be the same so if we were to for instance do here parent element and I say we’re going to get the same exact thing so you could use either in in this case and if I wanted to say like child Dot parent node dot style Dot uh back we’ll say background color and set that to hex value actually let’s do let’s do something a little darker yeah so we could do that all right so that’s pretty much it as far as accessing the parent because there’s only one parent node right when it comes to children you have multiple children nodes now as far as siblings siblings I’m gonna once again get the second item so I’m going to do that with document Dot query selector and we’re going to get the class child but we want to get the nth so nth child two that’ll give us the second one so just a make sure that’s correct let’s set output equal to second item okay so we have the second item now if we were to get the oops Let’s uh let’s bring this up here so if we were to get the um next sibling right not next element sibling but next sibling it’s a text node okay because of that white space because we’re right here right now and the next node not the next element would be this but the next node would be the white space here if I were to take this and and close that white space then yes the next one would be the element and then just like we have next sibling we also have previous sibling which is also going to be a text node so hopefully this gives you a good understanding of nodes in general versus element nodes which is what we looked at in the last video and for the most part you’re going to be working with element nodes so the other properties we looked at like next element sibling previous element sibling parent element uh what else children as the as the an HTML collection as opposed to these child nodes so that stuff you’ll probably be working with more but again I want this to be a front to back course I want you to know everything you know as far as I know all right so that’s it in the next video we’re going to be looking at actually creating elements from our JavaScript okay so we can select elements from the Dom using multiple methods we can navigate to related elements using certain properties and we can manipulate Elements by changing their inner text in our HTML we can change the Styles now I want to show you how we can create elements in JavaScript so we can create any Dom element that we want and then insert it into the document wherever we want using specific methods so in many cases you’ll want to create a new element and then insert it into the document on some kind of event so an example would be with this shopping list ultimately we want to type something in here click the button add item and have it get added to the list now we’re going to go over events in the next section but the next few videos in this section we’re going to do some of the stuff that usually would happen after an event is fired off all right I just want you to know how to insert thing to remove things Etc create things alright so let’s jump into our script JS for this section and what I’m going to do is create a variable here called div because that’s what I want to do is I want to create a new div so we can take our document object and there’s a method called create element so we’re going to run that but we need to pass in the type of element that we want to create and of course it’s going to be a div judging by the name of the variable now we can console log that div and this doesn’t do anything to the page just yet all it does is basically just creates it in memory from our JavaScript it’s not placed in the page just yet now we can add attributes to this div so I’ll go right here and I’ll say let’s do div Dot and we’ve already looked at some of these like class name so let’s say I want to add a class name of my element and if I save now you’ll see that I have a div and it now has a class attribute of my element if I wanted to add an ID I could say div ID and set that to we’ll just use my element again so now it has a class and an ID we can also use the set attribute remember that set attribute method so we can say div dot set attribute and let’s say we wanted to add a title to the div and we’ll just say my element and if I save that now you can see it also has a title so you can create it and then you can add whatever you want to it now as far as what I want to put in it because right now that it’s just an empty div so we can add something to it by using well there’s a few ways to do it the the easy way to do it would be to use inner text so we could do like div Dot enter text and set that to whatever hello world if I save that now you’ll see in the console this div has the text of hello world however using inner text is not the best way to do this when creating a new element it is it’s really meant to Inner text is really meant to get and change the text of an already existing element it’s better to create a new text node with the create text node method and then append it to the element okay because remember when we talked about nodes there’s element nodes there’s also text nodes and we can create those so what I’m going to do is just comment that out and let’s create a new variable called text and set that to document Dot and then let’s say create text node and then in here we’ll put the text that we want in it which will be hello world okay and then we need to add that text node to our div and we can do that by using the append child method so we can say a pen child and then text I save and now down here you can see that hello world has been put into this div now a pen child is a very important method that you’re going to need to understand because you’re going to use it all the time and it’s it’s easy to understand it appends a child to whether that’s an element or whether that’s a tech node a tech node a text node it appends it to or inserts it into whatever this is so in this case we’re putting the text inside of the div now we want to use a pen child to put it on the page as well and where you want to put it or what you want to append it to is is up to you it could be anything so let’s get rid of this console log and let’s say we just want to put it at the at the end of the body or you know at the end of inside of the body we could just do document.body append child and then pass in our div and if I save that you’ll see that hello world is now put at the very bottom so if we were to inspect our element here it’s right before the the ending body tag okay it’s above the scripts and stuff and the live server stuff but it’s after everything else all right now if you wanted to put it let’s say at the end of this UL this this unordered list then instead of document.body we could do document and then we could select let’s say query selector and select the UL and then we could just uh just say a pen child and then append the div there I save and now it’s it’s going to be inside of the UL at the very end now what I want to do in the next video is actually insert an item that looks just like this with the the text and the the button so I’m going to actually give that to you as a challenge because everything you need to know we’ve already gone through and and most of it is right here for you to be able to do that so we can do it as a challenge if you don’t want to you just want to follow along that’s absolutely fine but that’s what we’ll do next all right guys in the last video we scratched the surface on creating elements and adding them to the Dom and there’s two main methods for that one is create element which allows us to do just that and then also a pen child which will allow us to append whatever we want to any element that we want now in this video I want to show you I want to get more deeper into that and show you how we can create a function to add a new list item to this shopping list and it has to include not only the the title of the the item but also the button this is a button that has an icon within it so it has to be the title the title and then the button and then also this I tag with along with these classes and I’m going to show you two ways to do it one is kind of a quick and dirty way of doing it which is using inner HTML and the second is a cleaner and more performant way of doing it where you’re creating all your elements not only the Li but also the button and and the eye tag here all right so and I’m not saying using enter HTML and doing it this the quick and dirty way is horrible it’s not you see it all the time but there is a better way to do it so ultimately we want to have a function which I’ll run down here called create list item and we want to be able to pass in whatever we want like let’s say eggs all right so let’s create the quick and dirty way first so we’ll say function create list item it’s going to take in an item now at the very least you have to create your Li element right I can’t do this I can’t say Li and set that to a string of let’s say Li at our Li tags here and then put in um actually we would use backticks here right because we want to put our item in here okay so we just have a string with list items and the item and then I want to append that to the to the unordered list so I would say document Dot and then we’ll use Query selector to get the UL uh we could do UL but it has a class of items so that’s more specific and then we can do append child and if I put the LI variable in here which is this this string let’s see what happens and this is this is what messes a lot of people up in the beginning it says fail to execute a pen child on node because the parameter one is not the type of node okay what I passed in here this Li is not a node it’s simply a string so this has to be a node meaning we have to actually create the element node and we do that with create element so we want to pass in here Li now the easy thing to do here the cheap thing to do is to just take Li and then set the inner HTML of that to a string or a template string and then I could just copy like all of this everything inside one of these Li tags and then replace apples with whatever that item is all right if I save that let’s see create element oh I forgot document all right so now if we look at the list you see eggs has now been added so we created an ally element node and then we just said well we want the inner HTML to be this and then we simply appended that Li node so next I’m going to show you a better way of doing this a cleaner way and that is to create all of the elements not just the LI but also the button also the I tag here and add the classes so let’s uh let’s call this something different so that we can run both we’ll just say create we’ll say create new item instead of create list item and it’s going to take in an item and let’s just call that down here so we’ll pass in say cheese and we’re going to call create new item all right now to start off here it’s going to start off the same we need to create our list item all right so we’ll say document Dot create element and we’re going to create our list item now we also have a button and an icon so let’s create the button as well I’ll say button equals document dot create element and we’re going to create a button all right and then that button has classes so we can say button dot class name and set that to a string of classes which are going to be these so I’ll grab those and paste those in and we should be able to console log here if we want the button just to see so we have a button with classes on it right now we also want an icon so let’s say const icon and set that to document Dot create element and that’s going to just be an I tag and then that also has classes on it so we’ll say I dot class name and set that to let’s see these two classes right here so we get the x mark all right so we’re setting that I’m sorry that should be icon I was wondering why it was white so now uh oh and one thing we I forgot to do is the text the text for the the LI is going to be a text node right so we’re we’re creating the LI element we’re creating the text node we’re creating the button element and we’re creating the icon element instead of just setting the inner HTML to whatever so for the text node let’s do we’ll just take the list item and then append we’re going to append child because the text node goes inside of it and then we can say document dot create text node we could put this in a variable if you wanted to and the text node is just going to be whatever the item that’s passed in here all right so now we need to put the icon right the I tag needs to be appended inside of the button so we can just say button dot append child and we’re going to pass in here the icon and then the button needs to go inside the list item right we have the list item the button will be appended inside that so let’s say list item dot append child and we want to pass in the button all right and if we do a console log right now of the list item well actually let’s look at the inner HTML in our HTML of the list item and that’s that’s the text node then we have the button with the classes and then the I tag with the classes so the only thing left to do now is to append that to the Dom to uh to the UL which is what we did at the end right here so let’s just paste that in and save and now you see cheese is added now is this a huge deal in this situation no it’s not just know that using inner HTML so using this this first method causes the web browser to re-pass and recreate all the Dom nodes inside the UL element so this is less efficient than creating new elements and appending them so the second way is going to be more performant also setting in our HTML HTML will not automatically reattach event handlers to the new elements it creates so you would have to keep track of them manually I know we haven’t gotten into events yet but it can cause some issues with uh with attaching event handlers but again I’m not going to sit here and tell you that this is a horrible way of doing it and you will see this quite a bit all right now in the next video I want to take it a step further and instead of having just a single function I want to create a separate function for creating the button and creating the icon making it pretty reusable if you want to create other buttons and icons and also just making it more readable all right guys in the last video I showed you a couple ways to add a new list item to our shopping list and one of the ways was kind of a quick and dirty where we just used in our HTML On An Li node and then we also had this function here where we create the LI element the button element icon text node and we just append them all and then ultimately append to the Dom so when it comes to clean code I think a lot of it is preference you know so obviously some things are objectively wrong or right but I think a lot of it most of it comes down to the developer’s preference so in this case if you wanted to keep this as one function that’s fine but to me I think it’s cleaner to cut it down where a function does one thing so we’ll have this create the item but then we’ll also have another function to create the button and another function to create the icon and then it makes it more reusable if you want to create a button or an icon somewhere else all right so this is completely optional what I’m doing here I just want to give you a couple different points of view you know so it’s up to you on on how you choose to write your code but I want to give you the options so so let’s create a function called create button okay because I want this to be a separate function that takes in the classes because each button has classes and then also the same thing with icons so let’s create another function called create icon all right and then basically all we want to do these two lines here we’re creating the button and then we’re adding the classes I’m going to cut that put this into here and then the classes we’re going to cut and then set button dot class name to the classes that are passed in as arguments all right and then ultimately from here we just want to return return the button and then what we can do in the create new item is just set a new variable of button to the return value of uh create button and then we can pass our classes in if I save that we’re going to get the same exact thing now I want to do the same thing with icons with the icon so I’m going to grab those two lines and in our create icon let’s paste that in and I’m going to cut these classes set that to the classes that come in as arguments and then return the icon and then that way we could come up here now this is another thing that you can you have preference on if you want to have the icon or create icon function called in here or in the button because the icon is inside the button so I’m going to choose to actually do it within here so I’ll say const icon set that to create icon and then pass in the classes and then this line here where we’re taking the the icon and appending it to the button that is going to go down here in this function okay so now if I save this we get the same result but to me it’s a little cleaner okay we have a separate create button and a separate create icon we’re just setting the button to the return value of of the create button we’re appending it to the list item and then ultimately we’re appending the list item to the the UL and the Dom all right so if I were to call another function here create new item and we’ll put in I don’t know sauce save that and you’ll see that gets added so it’s completely up to you I’ll talk about like clean code practices and stuff throughout the course but like I said I think a lot of it is preference all right guys so when it comes to inserting elements into the Dom we’ve looked at a pen child which is very common you’ll probably be using that a lot but there are other methods as well that you can use and I want to show you those in this video so the first three are they’re all related it just it’s the only difference is what you’re inserting so we have this insert adjacent element if you’re inserting a new custom element insert a Json text if you’re inserting text and insert a Json HTML if you’re inserting HTML so the way these work is they take in a position which is going to be one of these four so here I just put this example of a paragraph and if you choose to insert before begin it’s going to go above the paragraph okay or whatever element you’re using as a reference and then after begin would be directly inside of it at the top above all the content and then before end would be after the content but still within the paragraph and after n would be after the entire paragraph or whatever element all right so let’s start off with the insert adjacent element and I’m just going to create separate functions to run for each of these so this one will call insert element just so we’re not in the global scope and first thing we need is a reference element on the page so where do we want to insert our new element let’s say we want to do it before this filter items input so we need to bring in that filter items input so let’s say document Dot query selector and I believe that has a div around it with the class of filter so we want to choose that all right then we want to create our new element and this could be whatever anything you want to put on the page whether it’s a new list item or it’s some data from an API whatever it might be in our case I’m just going to create an H1 so let’s say document dot create element and we’re going to create a new H1 and then I’m just going to add some text to that with text content so let’s set this I’ll just put the the name of the method we’re looking at as the text all right and then to insert it we’re going to take the filter and then that’s where we call insert a Json element and it’s going to take in two things the first is going to be the position which is going to be one of these four I’m going to choose before begin all right so that that’ll put it right above it and the second is the element we want to insert all right so now let’s just run this function so that this code runs and we’ll say insert element save that oops and you can see that my H1 has been put above the filter form if I change this to let’s say after end it’s going to be put below it all right so it’s just another way to insert content onto the page through JavaScript now the text insert adjacent text works in a very similar way so let’s create a function here called insert text and we’re going to figure out what text do we want to choose or what element do we want to choose to put our text before or after I’m going to choose the first list item here so let’s say const and say item and document dot query selector and we’ll just put an Li here we could do Li colon first Dash child either one is going to give us the first one and then on that item we’re going to run the insert adjacent text method and that’s going to take in a position let’s say we’ll do after end and then we can put in I’m sorry not item whatever text we want which I’ll just do I’ll just do the name of the method save that actually we have to run it so let’s come down here insert text save that and now you can see that it’s after the first list item if I change it to before begin then it goes above it I can also do after begin that will put it inside or before end which will put it inside at the bottom and this is similar to what a pen child does right so for HTML that’s just pretty much the same thing we’ll say insert HTML and let’s choose let’s choose the clear button down at the bottom so we’ll say clear BTN and document dot query selector and it has an ID of clear and then on the clear button let’s say dot insert adjacent HTML and it’s going to take in a position so let’s say before begin and then we can just pass in basically a string with HTML so let’s put an H2 and we’ll say insert uh insert adjacent HTML and close our H2 save that I keep forgetting to run it insert HTML there we go so it’s put before if I do after then it’s put after okay so again these all work and they work the same way it just depends on what you’re inserting an element a text just regular text or HTML and this is insert HTML or insert a Json HTML works like in our HTML now there’s another function or method that I want to show you called insert before which is similar to a pen child and how it works but it’s a little more complicated because you what you do is you define a parent or you bring in a parent and then you choose the item inside that parent that you want to insert your item before all right so let’s create a function called insert before item and we’ll create the parent or select the parent which I’ll use the unordered list so let’s say document Dot um query query selector and then we’ll choose the UL so that’s the parent now we want to create the element we want to insert which will be a list item so we’ll say document Dot create element and create a list item and I’m just going to add some text to that so we’ll say text content and set that to set it to the name of the function method we’re looking at and then what we do is Select an item inside the parent where we want to insert before so let’s select the let’s get the the third item so I’ll say const third third item and we can do that with document dot query selector and then I’m going to do Li and then we’ll use nth Dash child three okay so that will give me the third one and what I want to do is insert my my li I want to put it before this third item insert before that what’s weird about this is you call it on the parent so on the UL is where I do my insert before uh insert oops insert before and then that will take in your element whatever you know we’re putting in which is our Li and then it takes in the reference which is the third item so if we run this insert before text or what is it insert before item okay and now you’ll see that Oreos was the third one right this is the first one second one third one and I chose to insert before that third item so it put that this is my element my new Li it put it before that third item what’s kind of strange is that you call it on the parent with a pen child you don’t do that you just basically select you know the item that you want to put it inside of and then you call a pen child on that now you might think that since there’s an insert before where is it right here insert before that there’d be an insert after but there isn’t so what we’re going to do in the next video and you guys can look at it as a challenge if you want to try it beforehand is to create our own custom insert after all right so we’ll do that next all right guys so this video can be looked at as a challenge if you want to try it yourself or you can just follow along like you would any other video so we saw in the last video the last lesson that there’s a bunch of different methods we can use to insert elements and other things like text and HTML onto the page and insert before was one of those now you might think that because there’s an insert before there’s an insert after but there isn’t so what I want you to do is create a custom insert after function where you can pass in a new element if you look down here at this example code here if you pass in a new element like this Li that we created and then some item that already exists in the Dom your new item should get put after the the existing so in this case I’m selecting the first li as the existing item and I’m passing my li here in as the new item so it should get put after the after apples okay after the first item and you can use new L for your first uh parameter and then existing L for the second now as far as hints you can remember some of the properties to get parent and sibling elements okay remember we looked at that a few videos back and you can combine some of those I’m not going to say which one with insert before so if you combine these together there is a pretty simple way that you can make this work and you can insert a new element after an existing element all right so if you want to pause the video and try it you can if not just follow along and I’m actually going to copy let’s see I want to go back to that because I just want to copy the this code right here because I want to run this exact code so paste that in and now we want to create our function which is called insert after so insert after and that’s being called right here which is getting passed in this custom element that I want to add to the page so we’ll call that new element and then the next thing we’re passing in is an existing element which is the first list item so let’s say existing element all right now remember some of the the properties we looked at such as parent element so if I were to console log my existing element and then the parent element of that I’m going to get the UL okay so I have access to that unordered list and you could use parent node in this case as well if I do parent node that’ll give me the same thing so what I want to do is take the the parent element so existing l dot parent element and then I’m going to call on that insert before okay so remember this from the last video what insert before takes in it gets called on the parent and then what it takes in is the new element that you want to insert and then whatever you want to put it before now obviously we want to put it after that’s what this function is supposed to do but we can go ahead and take the existing element now if I run that and save it insert me after it gets put it actually gets put before apples which obviously isn’t what we want we want this to insert it after but all we have to do is simply add on to the existing element the next sibling property save that and there we go now it’s put after because if we put our new element before the the existing elements next sibling which is the next one orange juice that’s the same as putting it after apples okay so hopefully that makes sense and that’s why it’s important to understand these properties like parent element and next sibling and methods like insert before now I’m not saying you have to remember all these right now but at least know that that they exist and know that you can go on the mdn docs and you can look them up if you need to and and I still need to reference this stuff even for this course there’s plenty of stuff that I had to go and reference but I know it’s there and I know that these things are possible and I’m sure that for some of you this this challenge seemed like really difficult where you didn’t even know where to start but then you see the answer and it’s like one line it’s it’s easy so hopefully this this helps some of you guys out let’s see in the next video we’re going to start to look at replacing elements in the Dom all right guys so we know how to insert elements into the Dom Now using multiple methods now we’re going to look at replacing elements and some of the methods that we can use for that so we’re going to be working with our shopping list UI again and we’re going to be replacing some of the list item elements in this in this shopping list and there’s of course more than one way to do this so I’m going to show you a couple now I’m going to create a couple functions just because we’re doing a few things so I want to be able to to run separate functions so let’s create a function and we’ll say replace first item okay so I want this function to replace the first item which right now is apples so first we want to bring in the item we want to replace so we’ll call this first item and we’ll select that from the Dom with query selector and just put in here you could do LI or you could do first child either way it’s going to select the first one and then we want to create our new element so document dot create element and notice we’ve been kind of repeating ourselves quite a bit throughout the this section and that’s a good thing because it’s drilling into your head how do I select elements how do I create them and start them and so on now we want to create a list item to replace it and I’m just going to add some text content and you can use text content or inner text and let’s just make that say replaced first now to replace and this again this is just one way we’re going to use the replace with function or replace with method so we call that on our first item because that’s what we want to replace and we’re going to call replace with and then simply pass in our new element all right so let’s run this function save that and you’ll see replaced first okay so that’s the first way of doing this is using replace with the next one let’s call this function replace second item and in this in this function we’re going to use outer HTML okay we’ve used inner HTML quite a bit and that pertains to the HTML that’s in the element outer HTML will also include the HTML for that element so in this case the LI tags so let’s get the second item first of all so second item and we want to get that let’s say query selector and to get the second one we could do Li and then use nth child and two so that’ll get the second item and then on the second item we’re going to set the outer HTML and set that let’s say Li and then replaced second Li okay so it’s it’s similar to setting the inner HTML except we’re also setting the outer tags if I save that actually I have to run it of course so let’s say replace second item and now you’ll see replace second now the next one I want to show you is is how we can replace all of the items in the list and there’s not a specific method we’re going to use for it what we’re going to do is Loop through all the Li’s with a four each and then change the outer HTML for each one and if you want to try this on your own of course you can do that as well so let’s call this replace all items and what we want to do is get all of the list items so we’ll just call this Li’s and then we’re going to use Query query selector all since we’re getting more than one and we want to get all the LI tags all right now since query selector all returns a node list we can use for each on that so let’s say for each and we pass in our function here and we’re going to pass in we’ll call this item but I also want to get the index as well okay and then here what we’ll do is just set the let’s say item for each item we’re going to set the outer HTML and let’s just set it to replace all okay and then if we run that down here let’s say replace all items and oh I forgot the Li tags okay so we could do that we could also use inner HTML like I could do item dot enter HTML and in that case I would just do replace all because I’m not replacing the the LI tags so you can see that does the same thing um if I wanted to choose a specific item and and do something else I could do that so for instance let’s say if the index is equal to let’s do the second one so we’ll choose the index one then Let’s uh let’s see we’ll put this actually I’ll just copy that and then let’s say this is the second second item else then we’re going to have replace all so if I save that now you’ll see second item now why don’t you guys go ahead and shorten this up so this for each right here we can have an implicit return we don’t need to use curly braces and we can use a ternary instead of an if okay so if you want to pause the video and try that you can but uh actually let’s go under the four each but all we have to do is say for each and pass in here function we’ll say for each item and we also want to get the index and then here we’ll we’ll just say the item Dot we’ll use outer outer HTML so we want to set that to a condition okay or a ternary so we’ll say if the index is equal to is equal to one then we want this this outer HTML to be list item and then second item okay else then we want this to be a list item and just say replace all or we’ll just say item like that okay so if I comment this one out and save then we get the same result it’s just a little cleaner and a little shorter now another way that we can replace something is by selecting the parent element and then using a method called replace child so I’m going to create another function here let’s call this replace child heading and what I want to do if we look at the HTML here in the header there’s an H1 that says shopping list so I actually want to replace that with an H2 so the way this works is we select the parent which is the header we select the item we want to replace and then we replace it with a new item so let’s go ahead and first of all select header so that’s going to be let’s say document dot query selector and that has I will just select it by the the element itself which is header and then let’s get the H1 so H1 and we’ll say header H1 and then let’s create a new element we’ll call this variable H2 say document dot create element create an H2 and let’s add an ID because I believe that has an ID or it doesn’t okay but we can still add an ID we’ll say dot ID equals app dash title and then for the content let’s say text content and I’m just going to keep the same shopping list okay and then all you have to do is on the header we can do replace child and we want to replace we want the H2 to replace the H1 all right so let’s run that function replace child heading save that and now this should be an H2 so if we check it out there we go H2 and it has the ID of app title okay so those are some of the ways that we can replace elements in the next video I want to show you how we can remove elements okay so now we’re going to look at removing Dom elements now just like with most of the stuff that we’ve talked about in this section the things we’re doing we’re usually going to do when we fire off an event such as click this delete button right here then we would remove this all right but I just want to show you that the methods to manipulate the Dom before we get into events and we’ll get into events in the next section so so there’s basically two methods I want to show you remove and remove child so they’re pretty self-explanatory remove is going to be called on the element you want to remove remove child is called on the parent element and then you pass in the item you want to remove so I’m going to give you a couple examples in the form of functions so let’s say we want to remove the clear button so all we have to do here is Select say query selector and we’ll select the clear button which has an ID of clear and then we can just call remove okay and then if I come down here and I say remove clear button and now it’s gone and you could put this you know you could put this into a variable like say clear button and then what you could do is just call on clear button variable removed same thing all right now the next one is remove child so I’m going to create a function called let’s say remove first we’ll say remove first item and we want to since we’re moving using remove child we want to get the parent which is the UL so let’s set that to document dot query selector and select the UL and then select the item we want to remove I’m going to call this variable Li and then as a selector we’ll pass in Li and we’ll do first child or you could just do Li so that’ll select the first one and then we want to call on the parent on UL we want to call remove child and then we’ll pass in our Li and then if I call that let’s say remove first item and now you’ll see apples is gone so that’s remove and remove child now we’ll do a couple other things just to you know explain it a little bit further so let’s create a function and let’s just call it remove we’ll just call it remove item and then I wanna I wanna pass in an item number or index and it’ll delete that item right so if you want to try this yourself then you can pause the video and do that but I’m going to comment out this remove first item so we have our apples back and what we’ll do is I’m going to show you a couple ways to do it we’ll use remove child in this one so we’ll get the UL so UL equals document dot query selector we want to get the UL and then for the LI let’s see I’ll just copy this down the LI we want it to be the specific item number and I want the item to be one two three four so so what we could do one of the ways we could do this is to put in backticks here for our selector and then do Li and then say nth Dash child and then in here we can put our variable of item number so that way if we come down here and we call remove item and we pass in one and save let’s see that didn’t work oh we did I didn’t actually call the remove so UL dot remove child and pass in the LI variable and now apples is gone if I pass in 2 then orange is gone all right now another way to do it is let’s see I’m gonna I’ll just copy this but I’m going to call this remove item 2 I guess and instead of we’ll still use remove child but instead of passing the variable into this pseudo selector I’m going to query selector all because remember what that gives us if I select all Li’s is an array-like structure called a node list and we can access the index so I can do this and what this will do is put the very first one the zero index which is Apples into this Li and then I I’ll remove that so to give you example let’s say remove item two and it doesn’t matter what I pass in just yet I’ll pass in one but Apple’s is still gone because I have 0 here so what I want to do is this item number I’m going to put that in here however remember it’s zero base so if I pass in one here like I am right now and I save it gets rid of the second one which is orange juice because this is zero base but I’m not making this like I don’t want to pass in zero so all we have to do is take that item number and just subtract one from it so now if I pass in one apples is gone if I pass in two then orange juice is gone all right now I’m going to give you one more example so let’s say function remove item and we’ll call this remove item three it’s going to take in item number now I don’t I’m going to use remove in this one instead of remove child so I don’t need to get the parent so what I’ll do is uh I’ll just copy this line here and I’m going to get all of the list items so I’m going to just get rid of these brackets here so we’re getting all the list items and then we can simply do Li which is a node list which is array like so we can say item number subtract one because it’s zero based and then on that item or on that element we’re going to just call remove so let’s go ahead and say remove three we’ll put pass in a one here and that should get rid of apples if I pass in 2 gets rid of orange juice pass in three gets rid of Oreos all right and uh and we can really shorten this up actually we could say const remove item three let’s call it four so remove item four and let’s make that an arrow function that takes in the item number and then it’s gonna return let’s say document dot query selector all right so query selector all and then we’re going to pass in here item number minus one and then call Dot remove so if I come down here we call remove item four and I pass in one that didn’t work let’s see oh I forgot to put the actual Li in here and there we go so now apples has gone now orange juice is gone so this is just a shorter way of doing this all right so that’s it in the next section we’re going to start to look at events which I’m sure a lot of you have been waiting for all right so what I want to do in this video is look at some of the properties we can use to manipulate CSS classes and just our CSS directly which we’ve done a little bit of this already but I want to really just just drill it down here so we’re not using the shopping list UI we just have uh we have a paragraph that has a class of card I have just this background and border and then a UL that has a class of item lists and items because I wanted to have something that has multiple classes and then a button that says run now we’re going to go over events in the next section but I wanted to have an event a button click here because 99 of the time when you’re changing classes and changing Styles it’s going to be on some kind of vent it’s not just when the page loads you would use CSS to just simply add Styles when you use JavaScript with CSS is when you want to have Dynamic functionality if you click on something like if you wanna display a menu or something on click like a hamburger menu that’s where you would use these kind of classes and and style manipulation as far as the style sheet I just have just I just changed the font I have a class of hidden with display none you’ll commonly see this if you want to hide something then we have a class of card that just designs this background here with the border and a class of dark which will give it a darker background and I haven’t used that yet anywhere in here so let’s jump into the script and I just want to bring in what we need so I’m going to bring in the paragraph so let’s say document dot query selector and we’ll select the paragraph all right then we’re going to Let’s copy this down we’re going to grab the item list so we could either put UL in here but it’s better to Target a class or an ID so let’s say item list and we’ll call this item list and then I also want to get all of the items so we’ll call this items and then what I’ll do is on the item list I’ll call query selector all and we’ll select all of the list items all right now as far as the The Click event goes I’m going to select the button so we’ll say query selector and select button usually you should have some kind of ID because you probably have multiple buttons on your page but in this case it’s fine and then I’m going to do dot on click okay and again I’m going to talk about events all in the next section that’s what the next section is based on so don’t worry about it right now if you don’t understand it but we’re just going to set the on click event to run a function called run and you don’t want to put parentheses here because that will automatically execute it so up here let’s create a function called run and if I just do a console log here and then let’s open up our console if I click it you should see a one all right now this is where I want to show you the different properties so the first one is class name so if I do a console log here of let’s take the item list and let’s say class name and I click this it’s going to show me all of the class names okay it’s just basically it gives you a string of all the class names now you can set the class name as well like I can say item list and let’s say dot class name and let’s say I set it to that dark class all right now actually you know what I want to use the the paragraph for this so the text so if I click on run notice it applies the dark class and we can check that out right here but it took the card class away so this is always going to overwrite whatever classes you have there so if you do do it this way you need to make sure that you also put the existing classes so in that case I could do that and then that would keep the Cod class as well all right now A Better Way for dealing with this is to use the classless property the classless object which has different methods you can use on it to add and remove classes or even toggle classes so let’s look at class list all right now if I were to console log here let’s say item list Dot class list okay so I’ll click let me just um we’ll comment this stuff out for now so if I click that you’ll see what we get is a it’s actually called a Dom token list which is similar to an array it’s basically an array of our classes all right and I could even Loop through that with a Dom token list you can use methods like for each so if we say item list Dot classlist dot for each and I’ll say for each class then let’s do a console.log of that class so now if I let me just comment this this one out so if I click run now you’ll see it’s just going to log each class so you can take each class and do whatever you want with it in this case I’m just logging it out now to add a class like let’s say we want to do this same thing we want to add the class of Doc but we also want to keep the class of card so I could take the text and say dot class list and then there’s an ad method that we can use and I want to add the class of Doc so now if I click that and that runs you can see it still has the formatting from the card class it just added the new class of Doc all right now we also have a remove so if we do let’s say dot remove and let’s remove the card class which will take away the padding and the the border and stuff so what happened is it added the dot class and then it removed the card class so there’s no more padding now we also have a toggle class which is very useful so let’s comment that out and Let’s uh let’s say text Dot class list and then we’re going to use toggle and let’s toggle the doc class so this is good if you want to have like a a doc light switcher a lot of websites have those so if I click on run it turns dock if I click it again it then removes the class in fact let’s go ahead and take a look at that you see this paragraph click run and dark it’s added click it again it gets removed so that that’s something that is very useful when you’re creating dynamic dynamic websites now I could also do let’s say we want to toggle the hidden class so what that’ll do is when I click it it goes away click it again it comes back so pretty cool now there’s also a replace class so if I wanted to do let’s say text.classlist I don’t use this one as much but it is available so if we wanted to replace let’s say we want to replace card with Doc so it’s going to take in two arguments so if I click now you can see the card is gone there’s no padding and the dot class has been applied so it just replaced it now if I want to change the style directly let’s say change Style then we could use the style property and we’ve already done this a few times but let’s say we want to take the I don’t know take the item list and let’s say Style and let’s change the line height now in normal CSS you would do line Dash height but we can’t do that here so if you have multiple words we just use camel case so it would be line height like that and we’ll set that to let’s set it to three so now when I click the button you’ll see that the line height is applied so you can do that with any CSS style or any CSS property if I wanted to change let’s say I wanted to um do something to all of these list items what I could do is there’s a few ways to do this but I could Loop through these right so item list I’m sorry not item list items which is the query selector all and let’s say for each actually I’ll put some parentheses in here because I want the item and the index and then for each item you can do whatever you want so let’s say we want to style the color and set that to Red all right so now I click that and all the items turn red and you can Target specific ones like let’s say we want to say if the index is equal to two then let’s make that item Style color we’ll make that one blue so now if I click it you’ll see that the third item is blue because that’s the index of two all right so that’s really the basics of of just dealing with uh classes and style in JavaScript all right guys so now that we’ve looked at all kinds of methods and properties on the document object to be able to add change and remove things from the Dom now we need to learn about the actions that the user takes to make these things happen and those are called events and any interaction that the user has with your web page all the way down to the actual loading of the page is an event and we can listen for those events and create something called event handlers so in this section we’re going to learn about all kinds of events most and keyboard events form submissions event delegation and bubbling and and much more so with the knowledge between this section and the last section you’ll be able to create some cool little front-end applications and then after this section we’re going to start on the shopping list project and we’re going to build that from scratch all right so in this video I want to show you how to listen for events but first of all what are events so the official mdn explanation is that events are actions or occurrences that happen in the system you are programming which the system tells you about so your code can react to them so that’s kind of uh an Overkill of an explanation basically an event is just when something happens okay or an action and that could be anything from the web page loading to clicking on an element typing into a text field hovering over an element submitting a form closing a window dragging an element resizing an element etc etc so just about anything is an event and you can listen for those events so that’s what I want to show you how to do now so I’m going to close that up and I just have our our good old shopping list UI here with an empty Javascript file and there’s a few ways that we can add an event listener onto an element so the first way I’m going to show you is is not recommended I don’t think any JavaScript developer would recommend it because it’s not flexible it can also pose a security risk and that is to put the listener in the HTML file as an attribute so for example this this clear button that’s what I want to work with so we could put in here an on click attribute and then I could actually put a JavaScript expression right in here like I could say alert and say clear and now if I come down here and click the button I’m going to get an alert box with clear all right now obviously you can only put so much JavaScript in here so you could actually put a function like on click or let’s call it on clear and as long as I have my script file linked to my HTML here I can create a function called on clear and then I can alert and we’ll say clear items all right so if I come over here and I click again we get an alert box with clear items but again this is not recommended you don’t want to have your HTML cluttered up with what are called inline listen event listeners so we’re going to get rid of that and then I’m going to show you the second way which is to use a JavaScript event listener so with this we can select our element let’s see I’m going to keep the on clear here but I want to comment it out but I’m going to bring in the clear button because I’m going to use it in a few different places so let’s say clear BTN we’re going to select it with query selector and it has an ID of clear all right so what we can do to add an event listener within our JavaScript is to say clear button and then just do a DOT on click and on click is one of many event listeners and then you would set that to a function and then do what you want in here so let’s do uh we’ll do we’ll do an alert so we’ll say alert and clear items okay so if I come over here I click and I get my alert box and I didn’t have to do anything in the HTML so that’s the second way the Third Way is what I would recommend it’s the most modern way and it’s what we’re going to do in this for the rest of this course and that is to use the add event listener method and what that does is it just allows you to do just that you take an HTML element or a Dom element and you add a listener for a specific type of event so let’s comment this out for the moment and let me just say add event listener so we would once again just take the clear button or whatever we want to put the listener on and simply say add event listener and then this takes in two arguments it’s going to take in the type of event which in this case I want it to be a click and then it takes in a callback function so I’ll just put an anonymous function in here and then I’ll do an alert and we’ll say clear items save that and if I come over here and click I get the same thing all right gives us the same result now you can shorten this up we can go ahead and turn this into an arrow function so we can do that and since it’s just a one liner we can even get rid of the curly braces like that and that should still work all right so this is what I would recommend and another kind of Advantage with this is you can have as many event listeners as you want on the same event and let me just show you if I uncomment this and then I copy it and then let’s say I want to do I want another event listener on the clear button and this time I’m going to just console.log clear items all right I’m going to comment this out for a minute so we have two event listeners same event same element but they do two different things so now come down here and let’s open our console and let’s click and you’ll see we get our console log but I never get that alert okay if I comment the second one oh then we should get the alert now with add event listener we can have as many as we want so I’m going to just copy this down and let’s see instead of on this for on the second one instead of alert let’s do console.log and now if I click this you’ll see we do get the alert and then when it once I clear that up then the it console logs all right and the reason that it doesn’t run at the same time like you don’t see the log at the same time is because an alert is a blocking operation and I’ll talk more about that when we get into synchronous versus asynchronous code but just know that an alert is it’s synchronous and it’s blocking so nothing is going to happen until that’s cleared up all right but it does run both of them so that’s an advantage of add event listener now for these we put in just an anonymous function but we can use a named function such as on clear so I’m going to just uncomment that and I’ll just comment one of these and then instead of passing in this Arrow function as the second argument let’s pass in the on clear function now when you do this you don’t want to put parentheses if I do that it’s just going to execute okay the function gets invoked because we’re using parentheses so you just want to pass in the Callback you want to pass in the function name so that way it only fires off when you fire the event all right now there is a remove event listener method and you don’t have to use it every time you add an event listener where you do want to use it is when you have an element that you’re removing from the Dom like we learned about the remove method remove child if you’re doing that then it’s a good idea to remove the event listener first so what I want to do is is call remove event listener but I want to call it five seconds after the browser low after the page loads and I’m going to use a function called set timeout to do that which we haven’t used yet so it might be a little confusing but we will get into set timeout which is an asynchronous JavaScript function and we’ll get into that later but basically it takes in two things a function and then it also takes in the number of milliseconds that I want to wait to fire this function off and I’m going to say 5000 which is five seconds and then in here is where I want to remove the event listener so I’ll say clear BTN dot remove event listener and what I’m going to pass into this is the event which is click and then I also need the reference function which is on clear okay and which we we have up here okay so that’s the function being passed in to add event listener also the function being passed in to remove out of uh event listener so if I save that you’ll see that this works fine I’m clicking it it’s it’s you know the box is popping up but once we get to five seconds you can see I can no longer click it because that event listener has been removed now the last thing I want to show you before we make this actually function and clear these items is that we can trigger an event programmatically so if I wanted to have my script actually do the click instead of coming over here and clicking I can do that so I’m going to actually use set time mode again because I want this to happen after a certain amount of time I’m going to comment this set timeout and once again we pass in a function and also the length of time we’ll do five seconds and I’m going to take the clear button and then from here I can do dot click like that okay so if I save that and then we just wait five seconds there we go we see the the alert box okay so we have this this event to this click event and here we’re waiting five seconds and then we’re basically clicking this just from within our script rather than coming over to the browser and clicking the button all right because there might be some cases where you need to do that where you need to actually fire off an event from um you know from your script so now what I want to do instead of just having this alert clear items is make this actually work or we click clear and all of these go away so what I want you guys to do is pause the video and see if you can do it and see how many different ways you can make that happen just for from what we’ve learned so far there’s there’s many ways you could do it so just pause the video and see if you can do that all right so the the easiest way would be to just take the uh not the clear button we need to have the the unordered list so we’ll say query selector and we’ll select the uh unordered list actually I’m going to put this in a variable let’s say item list okay now when it comes to setting these in variables it’s all preference if you’re just using it once in one function then I mean I would probably just use document query selector and not put it in a variable if you’re using it a bunch of times in your function then do something like this if we’re using it a bunch of times in the script then put it at the top you know in the global scope but different people have different preferences so what we could do is simply take that item list and set the inner HTML to nothing that would be the easiest way to do this clear it all right it isn’t the most performant but you’re not even going to notice a difference because this it’s such a simple task so that’s the first way of doing this second is to bring in the the actual list items so we’ll say items and we can set that to item list and then use Query selector all and select all of the list items and then we could Loop through the list items so items dot we could use a four each and that’s going to take in function we’ll say for each item then we want to do an item dot remove okay so if I do that I click clear they’re all going to go away all right and then the last way I want to show you is using a while loop and I I guess this is the most performant way to delete multiple items like this so we’ll say while it’s it’s a it’s a way that I didn’t really use before a little while ago so we can say item list and then we can use the first child property to just check to see if there’s a first child if there’s a first child that means that there’s there’s a list item and then we can take the item list and use remove child let’s say remove child and then we can pass in the first child with item list Dot first child all right so we’re basically checking for the first li if it’s there then we’re going to remove it and it’s going to do that until there’s no more children and that just fired off because of this let me just comment that out okay so I click and they go away all right so that’s it in the next video I want to start to look at some other Mouse events other than just click okay so now we’re going to get into some of the mouse events that we have that we can listen for and we’ve already looked at click but there’s many others as well so I’m going to just pick something on the page to assign these event listeners to I’m going to use the logo so I’ll say document dot query selector and I’ll just select the IMG because it’s the only IMG on the page and then I’m going to put all my event listeners at the bottom of the page which is my preference if I have my event listeners hooked to a function I like to put the functions up top and the event listeners at in the bottom so let’s do a click just so just to be consistent and have all the mouse events I know we’ve already looked at it but we’re going to say add event listener and we’re going to listen for a click and then we’ll have a function called on click all right and then we’ll create that function up here I’m going to use Arrow functions just to keep them shorter so I’ll say const on click and then I’m just going to do a console.log and say click event all right so if I come over here to the logo and I click I’m going to see click event so the next one I’m going to show you is double click now what we call the function like right here I can call it anything we’ll call this on double click this is is where you need to be specific so double click is DBL click and it’s all lower case it’s not like this right if you if you’ve used jQuery before and used events there it was camel case but in this case it’s going to be all lower so let’s copy this down and we’ll say on uh double click then let’s say double click event so now if I come over here and I if I click once I get click event if I double click I’m still going to get my my two click events but it’s also going to fire off the double click event all right and just to make this a little more fun let’s actually put some curly braces here make a code block and let’s have it do something else so I would encourage you if you’re just learning this stuff I’d encourage you to to just create events and just do some weird stuff you know like maybe we can take the body uh background color and change it so we’ll say style Dot uh background color and we’ll set that to purple so now if I come over here onto the logo and I double click we get a background of purple and maybe we want to toggle it so what we could do is put an if statement around this and say if it’s not equal to purple then we’re going to make it purple and we’re also going to make the text White so go like that and then set the style color to white else because we want to be able to toggle it so else then we’re going to set the background to White and we’ll set the we’ll set the text color to Black all right so now if I come over here and I double click changes the background in the text color I double click again it goes back to White and I can toggle it right because we just we have an if statement we’re checking that background color all right so I mean I know that’s kind of pointless and stupid but it helps you learn so I would encourage you to just do stuff like this as you’re learning all right the next I know that was kind of a tangent but the next one is to if you want to right click and the event is not called right click it’s called context menu because that’s what it usually does is open up a context menu but I’m going to call the function here on right click and then I’ll just um we’ll grab that and let’s change this to on right click and we’ll say right click event and again if you want to do something else other than just a console log you can but you’ll see now if I right click the context menu opens up but it also shows me the the console log okay the next one is the mouse down and mouse up so let’s do mouse down and then we’ll call this on Mouse down now oh we need to create our function say mouse Mouse down event and we’ll call this on Mouse down okay so what this pertains to is when you when you take your mouse and you just click and hold see I’m holding the the the left button down right now that’s the mouse down okay when I let go then it’ll say click event because the click consists of down and up a mouse down is just when you hold it down because you might have something maybe you’re creating a game where you like click and drag or something like that and you want to have something happen when that as soon as that mouse goes down and at the same time you can also have a mouse up so let’s say on Mouse up and we’re going to listen for Mouse up and we’ll just copy that up on Mouse up and Mouse up alright so now if I come over here and I click and hold I can see the mouse down event when I let go we’re going to see The Click but we also see the mouse up okay so most down Mouse up next one is wheel so if you want to have an event on the mouse wheel and the event is is called wheel so bring this down and let’s say on Mouse wheel okay so now if I just if I scroll and I’m not over that the the logo the the item with this that this is on then it’s not going to do anything down here but if I come over it and I scroll now we’ll see the mouse wheel event and it’s going to fire every time I do a little you know a little scroll or whatever so those are are the events for the buttons now we also have events for hovering there isn’t an actual hover event that I know that for me back in the day when I learned JavaScript I also learned jQuery at the same time which I wouldn’t recommend and there’s a hover event in jQuery but with JavaScript you have Mouse over and mouse out so let’s say let’s copy this down and let’s say mouse over and then we’ll say on Mouse over and then let’s copy this down and say mouse over event on Mouse over all right so now you’ll see that when I go into the logo that Mouse over event fires off okay if I come out it doesn’t do anything if I go back in again so every time I go in then it’s going to fire that off now the out does the opposite so let’s say on Mouse out and the event is called Mouse out and out all right so now if I go in I get mouse over if I come out I get mouse out all right so that’s how that works and then the last couple I want to show you have to do with dragging so let’s do we’ll get more into drag and drop later but the first one I want to show you is drag start so we’re going to say on drag start and the event name is drag drag start oops and then let’s go up here and copy that down we’ll call this on drag start drag start event okay so now what I’m going to do is come over to the logo I’m going to click and hold and then move it okay so you see that it only fires off when I click and I drag it it only fires once it doesn’t like keep going when I’m when I’m holding it and moving it around that’s the drag event so that’s what I want to show you next so if we do let’s say on drag and just drag and then we come up here and just say on drag and drag events so now as soon as I grab it and I pull it’s going to say drag star but as long as I’m holding on to it even if I don’t move barely it still is just going to keep firing off and the faster I go the faster you know the event is going to go off so that’s drag and then you also have drag end for when it ends so let’s say on drag end and say drag and drag and all right so now if I grab it so we can see drag and then when I Let Go we should get that drag end oh I put I did camel case here so if I let go there we go drag end event so it’ll just keep dragging until I let go and then we get the drag end all right so those are Mouse events in the next video I want to before we move on to like keyboard events and stuff I want to look at the event object so there’s actually an object when we fire off an event that we can get as uh as a parameter here that we can use to to get all kinds of information so I want to look at that in the next video all right guys so in this video I want to take a look at the event object that’s available to us when we add an event listener and then we run a function so these right here are just some of the properties on the event object that I want to take a look at we’ll get to that in a second but first let’s go ahead and take an element from the Dom let’s just do the logo again so that’s the image and I’m gonna add an event listener onto that so logo dot add event listener we’ll just use a click event and then I’ll pass in a function here now these functions that we pass in can take in an optional event object and you might see it as e you might see it as event you might see it as EVT e is usually what I use it’s just preference but it could it could technically be anything and then let’s just do a console log of that event object so now if I come over here and I click on the logo we’re going to see this in the console so this is the event object with a bunch of different properties and methods on it okay and these these are all in here but it’s not all of them I’m not going to go over every single one right now some of these you just will never use anyway now this doesn’t matter if you pass in an anonymous function like this or if we create a separate function like let’s say function on click so even if we do it this way we’re still going to have access to that event object so what I’ll do is just replace let’s replace this with that named function of on click and if I click on the logo we get the same thing all right now the first two that I want to show you are Target and current Target so Target is the element that triggered the event all right so basically the element that you click on so let’s go ahead and log e dot Target in this case when we click on the logo we’re going to see the image tag because that’s that’s what we clicked on now the current Target is the element that the event listener is attached to now in this case these are the same right so whether I do current Target or if I do current Target so if I do that I’m going to see image twice because it’s the same thing right it’s I clicked on the image and the event is also attached to the image now it can be different I’m going to show you that in a second but I just want to mention that you can use this e dot Target or current Target most of the time you’ll probably be using Target but you can use this to do certain things to that element so for instance I could take e dot Target and then take the style and change let’s say the background color and set that to Black so if I click this now you’ll see that the background turns black so if you need to access the event that’s clicked on you can use e dot Target and you can do anything to it as if it were just an element you brought in with query selector all right now as far as the difference here I want to show you I want to show you where it would be different so if we put on the body just document.body and then we add an event listener right so add event listener and we do a click event and then we have a function and then I’m going to copy both of these console logs here and paste this in now if I click on let’s say this this list item right here if I click on that oops I forgot to pass in the the event object if I click on that you’ll see I get two different things here because the the event is put onto the body and that’s what current Target is it’s whatever the event is attached to the Target is whatever I clicked and then in this case I click the LI which is in the body so basically what happens is events bubble up if I click on the list item that event bubbles up to the to the parent which would be the UL and then bubbles up to that pattern and that parent all the way up to the body up to the HTML and I’m going to go over event bubbling soon but that causes us to get two different things for Target and current Target if we put a listener on something like the body when we put it on the image there’s obviously nothing is is like is nested inside of that that would click on we’re clicking on the image and that’s where the event is but there is a difference between those two all right so let’s look at some of these other ones we have type so I’ll uh let’s see I’ll just comment these out and let’s console log e DOT type so now if I go and I click on the logo the type is a click so that’s that’s the type of event that was triggered okay so if you want to access that the timestamp so I guess we’ll just copy that down and let’s say time stamp if I click on it that gave me undefined that’s because it should be an uppercase s okay so it gives us a time stamp and that’s going to change obviously whenever I click on it but if you need to access that for some reason then we also have these positioning coordinates so client X and client y this is the X and Y position of the mouse click relative to the window all right so let’s try that let’s uh let’s do e dot client X so the x-axis is always going to be horizontal okay so it’s from right to left and then Y is going to be top to bottom so if we save that and let’s click on the corner of this this image right here and you might get something slightly different but what we get is 27 and 58. so what that means is my cursor my my arrow when I click is 27 over from the left on the x-axis and 58 down from the y-axis if I move down a little bit you’ll see now I get 26 for the X and I get 105 for the Y because I’m further down okay so that’s what that those coordinates are now we have some other ones as well like offset X and offset y that’s going to be the mouse click relative to the element all right so what I’ll do is um let’s copy these and then what are we looking at offset so we’ll take these and change that to offset and now if I click in the corner here I get 10 and 11 so I’m slightly over to the left and down if I go up a little bit and over to the left 3 and 8 if I come way down here to this corner 42.53 so it’s the coordinates of where I click within this element okay not from the page like the client but the offset is going to be within within that element then we have the page X and Y which is going to be the position of the mouse click relative to the page okay not the window but the page which is going to be very similar so uh if we were to let’s go let’s change this and this to page and if we come over here and click if I click Like right here it’s going to be from the page you know from the the y or the x is 29 and the Y is 61. now if I make this bigger to where this is pushed way over and I click now you see we get 503 on the X so there’s a lot of space right here and still 62 here that that’s not going to change unless I resize the browser the other way all right so that’s getting the page now you can also do the screen there’s a screen X and Screen Y and that’s going to be your entire monitor so if we were to do that and this is going to be different depending on the size of your screen I have a Ultra wide so the x is going to be pretty large so if I do that so we get 366 from the top and 2916 from the from the left all right so and there’s others those other properties on here but I’m not going to go over every single one right now let’s see I wanted to talk about the method prevent default that’s something that you’re going to use quite a bit when you’re dealing with forms and what that does is it stops the prevent default of the behavior and with a form when if you’re if you’re dealing with front-end JavaScript for validation or maybe you’re making a fetch request or whatever it might be and you don’t want the form to actually submit to the page then you would use prevent default okay you could even use it on a link so if we come over here to the HTML and they’ll just put a temporary link somewhere in here all right so let’s just say we have a link to say Google Google and save so right now if I click on that obviously it takes me to Google but let’s say I want to put an event on that link and I want to stop that that behavior of bringing me to google.com so I’ll say document dot query selector and it’s the only link on the page so I’m just going to use a and then let’s add an event listener oops let’s say we want a click event and then we have our function pass in our event object and then instead of going to the page I want to stop it with prevent default which is a method so we want our parentheses okay and then let’s say I just want to have a console log instead and just say link was clicked so if I save that now and I come over here and I click the Google link you’ll see it doesn’t take me anywhere because of this it’s it prevents the default behavior and then it will do whatever JavaScript I have underneath okay so like I said that’s really common when you have when you have a form that you don’t actually want to submit to a page because you’ll see it actually submits to this page you see how that changes to the the spinner you can stop that with event e dot prevent default which we’ll be doing quite a bit throughout the course now some of these values can be dynamic like the the client X client y if we have let’s say a drag event then that will constantly change so let me just give you uh give you an example here so I’m gonna see we’ll just add another event listener to the logo let’s say logo dot add event listener and this time I’m going to listen for a drag event remember we looked at that in the LA I think it was yeah the last video and then we’ll do on drag oops I don’t want to do that so we’ll create a function here called on drag and we’ll pass in our event object and then what I want to do here we could console log but let’s go ahead and add it to the page so we’ll select let’s say query selector and we’ll select the H1 and then let’s set the text content and set it to some back ticks so a template string and then we can say we’ll say x and then we’ll give the x value by putting in a variable or a JavaScript expression here of e dot client X remember because we have access to that event object so we can use that for anything all right then we’ll do y and let’s put in here e dot client y so now if I save and then I click on this and drag it you’ll see that the H1 now changes to the X and Y values so that’s how you can create really Dynamic stuff within the browser like games and and so on is tracking positions and using events but this is what I mean when I say just try out like stupid little things like this which obviously doesn’t make much sense you wouldn’t have this in a real project but it gives you practice on everything really creating events selecting items or elements using the event object whatever okay so that is the event object we’ll be using much more of it throughout the course in the next video we’re going to look at some keyboard events all right guys so now we’re going to look at some keyboard events we’re also going to look at certain properties on the event object when we use these keyboard events and the element that I’m going to work with is this item input right here so when we type in here we want to basically detect these keyboard events and there’s three main ones that I’m going to show you key down key up and key press so let’s start off by bringing in that input I’m going to call this item input and I’m just going to use get element by D just to switch things up a little bit because it has an ID of item input item Dash input all right so we have this element and now I’m going to take that item input and add an event listener onto it and let’s listen for the key press event and when that fires off then we’re going to run a function called on key press all right we’ll come up here and let’s create a function I’m just going to use an arrow function and we’ll say on key press and remember when you use an arrow function if you only have one parameter here you don’t need you don’t need parentheses around it although my editor will add them automatically when I save but let’s go ahead and just console log here for now we’ll just say key press so we know when that’s fired off and I’m going to go in here I’m going to just hit any key and hold it down so hit the letter K and you’ll see it it fires off if I Let Go nothing else happens it’s basically as when you tap any key and it doesn’t matter if you just tap it quickly or hold it down it fires off that event just once all right now the next two key up and key down let’s comment this one out and let’s look at let’s look at Key up first so we’ll say on key up it’s the key up event and then I’m just going to copy this down say whoops on key up and key up okay so now what I’m going to do is again just just hit a key and hold it and nothing happens yet but when I release then that fires the key up event all right and that function gets called so when you release is when this is this event now let’s go ahead and do the key down so key down and I’ll just whoops that’s not what we want I want to copy this down and we’ll call this on key down key down okay now I’m going to choose a key I’ll just do the letter H and I’m going to hold it down now notice it fires off but it keeps firing off as I’m holding it down until I release and then it stops so that’s the difference between key press and key down key press is basically just it as if you were to tap it once where key down it’s going to keep going if you hold it down now there’s a couple properties on this event object where you can get the key that’s pressed because in many cases you’re going to need to know that let’s say you’re creating a game where you can hit the arrow keys and you can move something in different directions so obviously you need to know what what arrows which keys are being pressed or you might simply have an input field without a submit button and you want to know when they hit enter so that you can do something so there’s many cases where you’ll need to do this so what we’re going to do is first of all let me just put the comments in here so this there’s actually three we can use there’s key there’s key code and there’s code all right now key is probably the easiest however there are some older browsers that don’t support this um I think you you’d probably be fine using it but you might want to use another one in combination or instead of it but let’s just do a console log here of e dot key so I’ll just type in let’s say B so you can see it’s logging in the console whatever I’m typing and you could do whatever you want with this like we could say uh document Dot I’m not going to keep this but just to show you real quick if I select the H1 and then we could set the let’s say in our text equal to e dot key and now if I type in here b r a d it’s gonna it’s gonna replace it it’s not going to append it we could have it appended if we wanted to but it’s just going to replace with whatever I type all right so again just something kind of cool you can experiment with but let’s get rid of this and I just want to show you if you want to test for a certain key what you could do is you could just put this in an if statement and we could say if key equals let’s say enter capital E enter and then we want to do an alert and we’ll say you pressed you pressed enter all right now in this case if I hit enter it actually is going to submit the the form to the page however alerts are they’re blocking they’re blocking events so it will fire the alert before it actually tries to submit so if I hit enter you’ll see that I get the alert if I type anything else it doesn’t until I hit enter all right so that’s key now for key code it’s a little bit different it’s going to give you an actual number a key code so I’m going to paste this link in here and this is a link to a page that will give you the key codes so you can see like enter is 13 shift is 16. so every key on the keyboard has one of these codes these key codes so if I wanted to for instance check for enter I could say if and then say e Dot key code so if e key code is equal to the number 13 then we’ll just same thing we’ll just alert and say you pressed enter and I’m just going to comment this one out all right so if I save that I type in here and I hit enter you can see that’s another way we can test it and then we also have code so for this it’s going to look like let me just we’ll console log e dot code so if I hit like the letter F it says key f key D if I hit the number one we get digit one so of course if we wanted to check for that we could say if and let’s say we want to check for if we hit the number one so we could say equal to and then the string of Digit one and then we’ll just we’ll do a console log and say you pressed one so now if I hit in here if I go two three four but if I hit one then we get the console log all right now there’s also a repeat property and you’re gonna usually use this on the key down because what it does is it it lets your script know if you’re holding a key down or not all right so if you just tap a key it’s going to be false if you hold the key down then it’s going to be true so what we can do is let’s just do an if here and we’ll say if e dot repeat and that’s going to be true or false so we can just pass that in then we’ll console log and we’ll say you are holding down and then I’m just going to concatenate on that e dot key so now if I click in here and I just tap let’s say the letter L you’ll see that nothing happens in the console however if I if I hit and hold l we get you are holding down L because that repeat property is true as long as I’m holding a key down so you can really just tell like whatever whatever the user’s pressing as well as how they’re pressing it you can also test to see if they’re holding shift or control or alt so let’s come down here and I’m just going to console log these so these are properties we have shift key control key and ALT key so let’s console log and I’m just going to put the text shift and we’ll do shift colon and then I’m going to just concatenate on the shift so shift key property all right so now if I come over here if I just hit the letter D we get shift false if I hold shift and hit D we get shift true okay so that you can tell if they’re doing these combinations same thing with control and ALT so if we say um what is it Ctrl so control and then we also have alt which would be option on a Mac so this will be ALT key all right so come over here and I’ll do just hit L everything’s false if I do control L you can see control is true if I do option or alt L true so you can tell that the key combinations and you can you could do an if statement here as well and of course you could say if e Dot say e dot shift key and we want to check if let’s say e dot key is equal to K and then we’ll just do a console log here and say you hit shift plus k so now I’m going to come in here and I’m going to hold shift and hit K it says you hit shift plus k all right so those are keyboard events along with these different properties you can use to to figure out which key is actually being pressed all right guys so now we’re going to actually build a little project using the the key code information that we learned in the last video so this is actually a production application at toptel.com developer key code and it says press any key to get the JavaScript event key code info which is the stuff we looked at in the last video so I’m just going to hit a random key I’ll use the letter L and what it’s going to give us this 76 this is actually the event dot key code remember we have a number for every every key and then down here you can see what you get for event dot key which would be L you have event dot code which would be key L we’re not going to do these other things which you could because these are also on the event object but what I want to do is kind of recreate this application and just show the event dot key the event dot keycode and the event dot code all right now what you’ll have in the starter file is simply the HTML and CSS if I hit a key nothing’s going to happen right now because it’s just HTML and CSS now this is actually from my 50 projects in 50 days course however in the course we did it kind of the quick and dirty way where we just used in our HTML and then set these three basically these three divs okay I’m going to show you that way but I’m also going to show you a better cleaner more performant way where we actually create each of these key elements in the Dom and then we insert them and we’re going to be using a 4 in loop we’re going to be using an object we’re going to be you know doing stuff we’re going to use pretty much everything we’ve been talking about up to this point so I think it’s a good project for this point in time now if we go to the HTML you can see I just have everything hard coded right and there is some styling just some very basic styling here I didn’t want to go through the CSS or type out the CSS but just a background color on the body and then each of these boxes are going to be a div with the class of key so I have the border the background and then we have a small tag which is going to be each of these so if we look at our HTML each of those those titles are in small tags okay but what we want this to do is be dynamic so that this changes this changes and this changes based on whatever key we hit now if you want to pause the video and try this on your own I would encourage you to do that but it’s understandable if you know if you’re just learning this stuff you might not be able to do that just yet so and again I’m going to show you two ways of doing it the first way is is really simple but I would actually recommend the second way so let’s say I’m just going to call this method one of doing this and there’s so many different ways you could do it so we’re going to take what I’m going to do is just listen on the window for an event all right because I don’t want we’re not going to have a specific element where you push a key like we did in the last video with the input form as long as it’s on the window then we want to fire this off so let’s say window dot add event listener and we want to listen for a key down event and then I’m going to call a function actually for this one I’ll just put the function right in here and I’ll use an arrow function so we want to pass in our event object and then what I’m going to do is take the insert element this right here and pretty much just create all this HTML but with have having this Dynamic these three items here these should be all com they should come from those those key code properties so let’s uh I guess yeah we’ll just bring the insert in right here so let’s say insert equals document Dot and we’ll use we’ll just use get element by D and insert and then I’m simply going to take insert and just edit the inner HTML so I’m going to set that to some back text and then all we really have to do is bring in this stuff as a template so I’m going to just grab these three divs with the class of key and cut those and for now as far as when you just come first come to the page we’ll just have a message that says press any key to get the key code okay so when we come to this to the to the website it’ll just show us this all right and then I’m gonna just paste in those three divs here and you might just have to kind of format this a little bit to uh to look a little better so we’ll just push these over all right now we just want to replace these three so the first one is going to be the E dot key so let’s simply replace that with our syntax our dollar sign curly braces and just say e dot key and then we’ll come down here and replace this and make this Dynamic so this will be e Dot key code and then this one will be whoops that should be money sign this should be e dot code all right and that should actually do it and if I come over here and I hit let’s say the F key you see I get f for the the key property 70 for the key code and key f for the code if I hit W if I hit n if I hit enter if I hit the the digit one now the one thing that you want to look out for is with the space so with the space button the key is actually just an empty string or a space in the string so what we can do here is just say right in here we’ll say if the uh we’ll we’ll have a condition so we’ll say if this is equal to a space like that then let’s just have the word space else then we’ll show whatever the key is so now if we hit space now space will get put in there instead of just an empty string I shouldn’t say an empty string but a space all right so that’s kind of the easy quick and dirty way of doing it and there’s nothing wrong with this I’m I’m not like one of those sticklers that thinks everything has to be perfect this works just fine but I do want to show you an alternate way of doing it as well so let’s go ahead and just comment this out and then I’m going to come down here and we’ll say method two and this is going to show us not just we’re going to touch on a lot of things that we’ve talked about so far so again we’re going to add on the window object we’re going to add an event listener and we want to listen for our key down and then I’ll put this in a separate function let’s call it show key codes if you want to keep it in uh you know just a regular Anonymous function that’s fine oops we definitely don’t want those so let’s come up here and let’s say function and show key codes okay we want to pass in our event object and then we want to select the insert again so I’m just going to grab that okay so we have our insert that’s what we’re obviously where we want to insert these Keys into and then the way that I’m going to do this remember there’s so many ways to do the same thing but what I’m going to do is create an object kind of a map I could even use a JavaScript map but we haven’t gone over that yet so let’s say key codes set that to an object literal and then for the key I want to use you know e dot key e dot key code Etc but since there’s a DOT we have to if we want this to work as an object with key value pairs we have to put quotes around that okay because that’s that’s the key it’s the title the actual key is going to go in here so e dot key now we do want to test for space again so basically we can do this same thing that we did right here so I’ll just put that in there it’s just going to test to see if it’s a empty space if it is it’ll just replace it with a string space so next we want the key code property so for the for the title here we’ll just say key code make sure you put quotes around that and the value is going to be e dot key code which will be the actual value and then we also want e dot code the value for that is going to be e dot code so what we’ll do now is let’s just do a console log of key codes and see what that gives us so if I come over here and we open up our console and if I just type something in I’ll hit the letter F so now we’re going to get an object that has our key our key code and our code if I hit the enter and so any key it’s going to just give us this object now I want to actually Loop through this object and remember to do that we can use a 4 in Loop because the idea here is to Loop through them and create one of those divs but one of these divs for each of these all right so I did with the class of key for each of these we want to create that we want to insert the text node which will be the whatever the value is also will create a small tag and append that into the key and add a text node to small as well so we’re just we’re basically like it we’re building it up okay we’re building it from scratch rather than just replacing the HTML so to do that let’s say four and what we want to have in here is let’s say let key in key codes which is the name of the object and I want to start to build up our our elements so let’s say cons div and we’ll set that to document Dot and we want to create a new element so create element we want to create a div element okay and then let’s add the key class to that so we’ll say div dot class name and we’ll set that to key right now we also want a small element so I’m going to create that as well say small equals document Dot and then create element and that’s going to be a small tag all right now for the text for that we want to put in here I’m going to create a variable for let’s say key text okay so this is basically um uh let’s see it’s it’s it’s this right here so what we want to be in the small text okay so let’s say key text and set that to document Dot and we want to create a text node and then pass in here just key okay because remember when we say let’s key and key code that pertains to this and this is a little confusing because when you look at an object it’s a key value but these are we’re also looking at Key Properties so it is a little confusing you could call this something else if you want now we also want the text for the actual key code that comes from the event object so that will be the value right it’ll be this the value of the object this is the key this is the value so let’s call this one we’ll call this one value text and then what we want to pass in here to get the value we can say key codes and then use the index of the key right so we could say key codes and then in Brackets put any of these and it will give us the value and that’s going to go in here now we just want to append the text nodes to the elements so let’s take the small element and let’s say a pen child and we want to append into the small the key text which is like the title which is this right here okay then we want to put the actual value into the key div so let’s say div Dot a pen child and we’re going to add in here the value text all right and then we need to append the small element into the div element so let’s say div a pen child again and we want to pass in here small and then the last thing to do is to add the div to the Dom so we’re going to take that insert element and we’re going to append child and then we’re going to put the div in there all right so let’s try that I’m going to save come over here I’m going to hit just uh we’ll hit the letter k now a couple things one we don’t want this to show two if I hit another key it just adds to it right every time it’s just going to keep adding so what I’m going to do is just clear the inner HTML of insert before we do anything so we’ll say insert Dot in our HTML and we’ll set that to just nothing okay so now when I hit a key let’s say the letter L the the welcome message goes away also if I hit another one it replaces it okay because what we’re doing is clearing everything before we actually before we go on and do any of this all right now obviously this is much easier than doing this but here we created you know we looped through what we need the data here and then we just created a new div element for each one and then inserted it into the Dom so in my opinion this is a better way of doing it but again I’m not bashing this this way either alright so hopefully you enjoyed this little project and we’ll do more of these throughout the course as we go all right guys so now we’re going to look at input events and how you can get the values for a form input and just for this video I’ve added a couple additional inputs so we had the text field right here which is this input and then I added this select list so just for a priority like a shopping item priority and basically I just have an ID of priority input and each option has a value 0 1 2 3 and then I also just added a check box here so we want to be able to tell if this is checked or not now if you’re submitting a form to some kind of backend technology like like PHP or node.js you would probably have like an action in your form and then submit to a page and then to access the value from the back end you would usually use this name attribute so whatever you have assigned to that now in front-end JavaScript it’s a little bit different you would not have have it submit to a back end because you would basically take over in your JavaScript and and do whatever and in that case you need to be able to get these these inputs all right so let’s go into our script JS here and I’m going to bring in those inputs so let’s say item input and I’m just I’m going to use document dot get element by D that has an ID of item Dash input okay and then I’ll just copy this down a few times the next one has an ID of priority input that’s going to be the select list so we’ll call this priority input and then this one here let’s call it check box and that has an ID I believe of check blocks and then I’m also going to select the heading the shopping list heading just so we can use it to output something if we need so we’ll call this heading and that I don’t think it has an ID so I’m going to use Query selector on that one and just select the the H1 all right so let’s start off with the text input or the item input so we’ll say item input and I’m going to add an event listener onto it now there’s a few different types of events or different events that you can use to be able to get the value and work with this input so you may see key down used so I’ll say key down I’m going to create a function called on input and run that so let’s say function on input pass in our event object and then for now we’ll just console log input so now when I come in here and I start to type you’ll see it’s going to fire off every time I hit a key every time I type in the field all right now you can use key down but I would suggest not I’d suggest using the input event which in this case will do the same thing it fires off whenever we type in but you can also use this on other other input Fields like a select list like a key down isn’t going to work for a select list because you’re not pushing any key so I would suggest using input for your your most your input Fields now to get the value remember we have we have access to e dot Target which will give us the actual Target so if I start to type every time I hit a key it gives me the Target element which is the the input tag itself now of course we don’t want that we want the value that’s typed in so there’s a value property that we can access with e.target.value so now if I start to type in here you’ll see that it’ll give me whatever is in the the form field and it’s giving me the entire input it’s not just giving me the key that I press like we saw in in the LA or the video before a last in fact if I were to do e dot key here shouldn’t even yeah it gives me undefined because it’s an input event if I do like a key press event then I can get the individual keys but see how it’s not like accumulating it’s not appending on to the last because it’s just giving me the key with this e dot Target value it’s giving me whatever is in the input so that’s what you want to use in this case all right now before I move on to the next input let’s just we’ll set the heading just to show you we can take this heading and let’s take the text content and let’s bind whatever isn’t whatever is typed in that form which will make this Dynamic where we can type and it gets put into the heading in real time which is which is cool but not very useful I mean it might be useful in some cases um but yeah and obviously that’s only on your own machine and that’s only you know in your browser and if you reload that’s going to come back now the next thing let’s look at the priority input which is the select list so let’s change this to priority uh priority input and then change actually no I’ll just leave it like that uh oh I spelled those wrong okay so now if I select something here what’s going to happen is it’s going to fire this input event and this is going to run and I can still get the target dot value with this with the select list so if I choose 2 you’ll see now the H1 is actually outputting two three so whatever I choose and it’s always going to be the value obviously you know in the HTML it’s not going to be what you put in the middle here that’s just for the user to see this is the actual value that’s being chosen okay now you can use input for this but there’s also a and that’s probably what I would recommend but there’s also a change event that you can use on a select list as well which will do the same thing in this case okay but uh I would I I’d suggest using input but I’ll just leave it at change just so it’s there and you know you can come back to it now check boxes work a little differently instead of using e.target.value there’s actually an uh checked E dot Target dot checked so what I’m going to do is on the check box say check box and we’re going to listen for an event so let’s listen for um we’re going to use input here but I’m not going to do the on input I’m going to do on checked okay and then we’ll come over here and we’ll say function on checked pass in our event object and then I’m just going to console log here e dot Target Dot checked okay now when I select it you’ll see that it would get true if I unselect it then we get false so it’s as simple as that to get if the check box is checked or not so what we could do is we could take the let’s say heading and we’ll say text content and let’s say if the check box [Music] um how should we do this we could put this in a variable we could say caused is checked and set that to that value and then say if is checked then we’ll say checked else we’ll say not checked so let’s save that and then I’m going to go ahead and check it and now you’ll see the H1 changes to checked uncheck it we get not checked all right now there’s two other input events that I want to show you and that’s focus and blur which has to do with clicking in and activating the input and clicking out of it and unactivating so clicking in it is going to be focus and and clicking outside will be blur so let’s use this on the item input so what I’ll do is change Let’s do let’s do Focus and I’ll change this to say on Focus and we’ll actually just copy this down and let’s say on blur and let’s change that to blur and then we’ll come up here and create a function called on Focus and usually the reason that you would use this is like if you want to have a specific outline or something like that and I’ll just do a console log here first and say input is focused right so oh I have to create my own blur as well so we’ll say function on blur and we’ll say do a console log and say input input is not focused okay so if I click inside I get input as Focus if I click outside I get input is not focused but again usually what you would use this for is for styling so I could say item input and say Style and we’ll say outline style and let’s set that to solid okay and then we’ll do let’s copy that down and then in addition to outline style let’s do the outline with and we’ll set that to say one pixel and then we can also set the outline color and let’s set that to Green and then on blur what I’m going to do is just set the outline Style so outline style we’re going to set that to none all right so now if I come over here and I click in here now you see I get this green outline if I click out of it then it goes away we can change it to red okay so it’s it this is good for for just visual effects and UI um and this is what I mean earlier when I said you know you’re not going to use JavaScript just to change the style of a web page a static web page that doesn’t do anything but you use it to make your page Dynamic to have things happen to have styles change and borders at it and stuff like that um but yeah so that’s focus and blur now in the next video I want to look at form submission so when we how do we you know catch when we submit this because if I just submit it as is it actually submits it to the page which you could you know you could have it submit to like a backend PHP page or something like that but of course we’re dealing with front-end JavaScript so I’m going to show you how to prevent it from doing that and then doing what you want all right guys so now we’re going to look at form submission in the last video we looked at events on specific inputs so that you could do something when something in that input changed now we’re dealing with actually submitting the form now as I mentioned in the end of the last video if you’re working with a back-end technology like let’s say node.js or PHP or something like that then your form tag may have an action that submits to you know some file on your back end it could be node.js it could be PHP or whatever it might be but we’re dealing with front-end JavaScript so what we want to do is go into our script file and let’s uh let’s get the form and I think the form has an ID yeah it has an ID of item form so let’s say const and we’ll get our form we’ll set that to document Dot get element by D and it has an ID of item Dash form all right so now we just want to add an event listener to that form and we want to listen for the submit event and when that happens we’ll have a function called on submit fire off so let’s add that let’s say function on submit pass in our event object okay now I’m just going to do a console log here and we’ll say submit and I’m going to open up the console and by the way I add I still have the priority select list here because I want to use that as well but you’ll see if I put something in here and I click add item watch down here so notice how it just flashed submit real quick that’s because it did do the console log but then it’s submitted to the actual file if you don’t have an action attribute on your form where you’re submitting to some kind of backend then it’s going to submit to this the same page all right now to stop that you can just say e dot prevent default okay we looked at this a while back this prevents the default Behavior so now if I put something in here and I click add item it doesn’t submit to the file okay it just it stops and then it does whatever I want in the front-end JavaScript which in this case is just a console log now obviously if you’re doing this you’re going to want to get the values that are being submitted to the form so there’s actually a few ways to do that I’m going to show you the first way which I really already showed you and that’s to use the the value Target dot value but there’s also a form data object that you can use as well so to use the the value what I’ll do is I’ll put the basically we have the item and we have the priority so we have two Fields so I’m going to set item to document Dot and we’ll say get element by D and that has an ID of item Dash input and then we also want the priority input and I’ll just set this variable to priority Okay so to get the value now obviously like if I console log here let’s do item and priority whoops okay and if I put something in here milk one so it’s giving me the actual element which I don’t want so we can just add on to this dot value you could do it like this where you set the initial variable to value and then print it or you can set it this to the element and then when you’re ready to use it you can then say dot value so both of these will work if I put milk one and add we get milk in one so it’s up to you on how you how you want to do this I usually do it this way but of course there’s all kinds of different use different uh scenarios now this is where you know your front end JavaScript this is where you do you’ll do some validation and you you should have both front end and back end validation if you’re submitting to some kind of backend API you should do validation here but you should also do it on the server side so whatever route you’re submitting to you want to check your form fields and and stuff like that on the server as well I’m just going to add dot value here just to be consistent all right and then what I want to do is just check let’s say if and we’ll say if item we just want to make sure it’s filled so we’ll say if item equals nothing and then we also want to check we want to do an or here not an and because we want to check either or and priority if that is equal to in this case let’s say 0 because it has an initial value right if we look at the form here select priority we don’t want this to be selected and that has a value of zero so we want to just check for that and then if if either of those are true then let’s just alert and we’ll say let’s say please fill in all fields and then we’re just going to return from that okay so if I leave both empty and I click add item I get please fill in all Fields if I just do milk and I don’t select the priority I get the fill in all fields and notice it’s not console logging these because I returned from the function here so let’s choose a priority and make sure we have that filled in and now we don’t get the alert and we get the console log so this is just very very simple form validation now I also want to show you how to use the form data object so what I’m going to do is create another function and I’ll call this on submit to and let’s have this now submit to that function and we do we still want to prevent the default Behavior and then what I’ll do is initialize a form data variable and set that to new and then form data with a capital f okay and then we want to pass in our form which we have up here so it this is in the global scope meaning I can access it anywhere else so I’ll just pass in my form here and then what I want to do is just console log that form data and see and show you what that gives us all right so if we submit this with milk Priority One and if we look in here it might not work how you how you may think we don’t just have direct access to the values like an object of values but in the Prototype you can see that there’s a bunch of methods here so if you just want to get each individual entry then you can use the the get method so let’s do that let’s set let’s say const item and we’re going to set that to our form data variable and then there’s a get method and what we’ll do is pass in the item into here all right now this item is actually the name so if we look at the input here the name so if you if you’re using the form data object you want to make sure you have a name for these the name for this one is priority so the next one just copy that down and set that to priority because that’s the name that we assigned and this is a this is a newer way of doing this and getting values so console log item and priority so now I’m going to again just choose milk choose one and add item and now I’m getting those values now we can also get all of the entries using the entries method which which is a little weird but I’ll show you how that works so let’s say const entries and we’re going to set that to our form data variable and then dot entries with parentheses because it’s a method and I’m just going to comment these out and then let’s console log What entries gives us so again I’ll choose milk one and add and what we get is an iterator so this iterator basically it allows us to to Loop through it or to iterate through it so an easy way of doing this is to use a four of so we could come down here and say four and let’s say let entry so we’ll call each entry of and then the iterator which is entries okay and then in here if I console log entry comment this one out and select milk and one so what it gives me is for each input or each item it gives me an array that has both the name and the value so if I wanted to access the value I could do let’s say entry and one because this is just a simple array with a zero index and a one index so if I do that and I submit this again then I get milk and I get one and of course you can get the title as well I should say the name so item and priority so you can get either one of those and there’s a lot more to the form data object that we might get into later but I wanted to show you at least the the basics of that but in most cases for something simple like this I mean just using dot value is fine now in the next video we’re going to get into something that’s pretty important and that’s called event bubbling so in this video we’re going to talk about something that is pretty important when it comes to handling events and that’s event bubbling so when we add an event listener onto an element that event moves up the Dom tree and if it finds a parent element that has a listener for that event it’ll fire that as well so even if we click on the the button it’ll bubble all the way up to the document okay now it’s a little hard to understand with just me explaining it so let’s I’m going to show you how that works so let’s grab the the this button right here in the form so we’ll say const and we’ll just call this button and we’ll set document Dot query selector and I’ll just say form and then I want to grab the button in the form all right and then I want to add an event listener onto that button so add event listener and we’re going to listen for a click and then we’ll just put the function right in here and let’s do an alert and say the button was clicked all right so very simple if we click that we get button was clicked now what we’re going to do is bring in the parent to that button so if we go to our index.html and we look at that button so right here this is the button that we clicked and the parent to that would be this div which is the second it’s the second div in the form so we can Target it like that I’m going to come up here and I’ll say const and we’ll just call this div and set that to document Dot query selector and let’s say in the form we want the second div so we’ll say div and then nth Dash child and pass in two so that’ll give us that second div and then what I’m going to do is add an event listener onto that so click we want to click event and then let’s just do an alert here and this time we’ll say div div was clicked all right so now what I’m going to do is come over here to just to the right of the button and I’m going to click that because that’s the parent says div was clicked but now you’ll see if I click the button I get button was clicked if I click OK I get div was clicked so what’s happening here is we’re firing off this this click event here and then it’s bubbling up and then any any of its parents that have a click event listener it’s going to fire that as well okay now to show demonstrate this even further let’s bring in the form because the form is apparent to the the div so let’s say form and set that to document Dot query selector and we’ll get the form and then I’m going to do the same thing I’ll just change that to form and let’s say form was clicked so now if I click on the form I get forms clicked if I click on the button I get button was clicked it’s going to Bubble Up div was clicked it’s going to Bubble Up form was clicked okay so we can even go a step further and say document.body and add an event listener onto that and say click and then we’ll say let’s do uh alert and say body was clicked so now if I click on the button we get button was clicked div was clicked form was clicked body was clicked so this pertains to this diagram right here where we click the button and that event is going to Bubble Up through all of its parents and anything that has a click event on it that will also get fired off now there might be cases where you don’t want this to happen because it will just kind of mess your application up so that’s where the stop propagation method comes in and that’s part of the event object so if we go back up to where we have our button let’s pass in our event object here and I’m just going to go after the alert and say e dot stop propagation okay so now if I come over here and I click the button we get button was clicked and then nothing happens after that okay so event bubbling is is really not that difficult to understand I know it does intimidate a lot of people that are getting started with with JavaScript but it’s just that it just bubbles up and if you have another click event on a parent that’s going to fire off unless you stop propagation now you should only call stock propagation if you have a reason for it for instance if we actually had a parent and child with that with the same event listener and don’t just call it for the hell of it and then there’s also a method called stop immediate propagation and this is used if you have multiple handlers on a single event and you want to stop the event for all of them but yeah so that’s event bubbling now in the next video I want to talk about something called event delegation all right so we’ve talked about events quite a bit and we know how to add an event listener onto a single element but what about when there’s multiple elements and a good example is for these list items if you want to delete these we have multiple delete buttons where we would want to add an event listener to now there’s a few ways we can do this we could basically select all of the LI tags or all of the buttons whatever it is we want to click on and then add an event listener for every single one which isn’t really efficient so this is where event delegation comes into play which is a a powerful event handling pattern so so I’m going to show you the the first way which is to basically just add an event listener on to everyone so let’s do that by selecting the list items and we’re going to say document we want to use Query selector all because we’re selecting all of the all of the LI tags all right and then what we can do is we can list through our Loop through the list items and say for each item and then just to show you if I console log here um we’re actually going to want to well no let’s add the list let’s add the event listener first so I’ll say for each item let’s add an event listener for click and then we’ll have our function here and I’m going to just console log e Dot Target so if I click on these you’ll see it’ll give me whatever list item I’m clicking on so now I can take that Target and I can remove whatever I whatever that element is whatever I’m clicking on so I can say e dot Target dot remove and we learned about the remove method a couple sections back so now if I click on let’s say orange juice goes away click on milk Oreos apples and of course this is just in the Dom it’s just in the in our browser if I reload that all comes back that’s because we’re not persisting that we’re not persisting the data or persisting those actions to any database or anything like that all right now as I said this isn’t really efficient especially if you have a ton of of elements that you’re putting a listener on instead we can use event delegation to basically add just a single event listener onto the parent and then Target whichever one we want to delete so let me just show you what that looks like so we’re going to select the parent which is the UL so let’s say document Dot query selector and we’re going to select the UL and I’m just going to comment this this out for now and we want to put the event listener on the parent so list dot add event listener and listen for click and then we’ll have a function all right so now I’m going to go ahead and just console log here and then I want to log e dot Target so I’m going to come in here and click and notice it’s still giving me the list item right I have the event listener on the UL so even if I click Like right here then it gives me the UL if I’m not clicking on the list item so what I can do is just Target the list item that I’m clicking on this e dot Target and remember Target is going to give you what you click on current Target is going to give you what the uh what the event listener is on so if I do current if we say e dot current Target and I click on the list item it’s still going to give me the UL so you want to make sure that you’re dealing with Target and we what we can do is just test and say if e dot Target dot tag name or class or whatever it is that you want to check if that is equal to in this case Li then we can just take that e dot Target which is what we click on and we can remove it from the Dom so now if I click on any one of these it just deletes them and now instead of adding multiple event listeners I’m just simply adding one and then I’m testing whatever it is I’m clicking on and then deleting that and and of course you’re not limited to just deleting if I wanted to let’s say let’s say instead of a click we do a mouse over and again we just want to check to make sure it’s a list item and then instead of removing it let’s change the style dot color and we’ll set that to Red so now if I come over here and I hover over a list item you see it will only it’ll change the ones that I hover over to red all right so that’s how you want to handle adding an event listener onto multiple elements is using event delegation now in this case we just use the list item so if I click anywhere it deletes when we actually build our project which is very soon we’re going to have to Target the button which is going to be a little bit more difficult because we have to kind of navigate to the child to the button and then there’s an icon in the button so it’ll be a little more difficult but it’ll it’ll be fun and we’ll you’ll learn quite a bit going through this project in the next video though I want to talk a little bit about some of the the events that we can use on the window and about just the window object in general all right so the window object we’ve we’ve looked at a few times and I think it was the execution context section where I showed you that that’s the first thing the execution context does is it loads This Global window object that has a ton of properties and methods and apis and also events now the first events that I want to talk about are page loading events on this window object so you’ll notice that in the HTML for this section or for this lesson I have the script tag in the head and this was something that was very common practice back in like the 2000s so I just want to show you if we if we keep the script tag in the head and then we select let’s say query selector and all I have on this page is just an H1 and and some paragraphs so I’m going to select the H1 and I’ll set the text content to hello world and I’m going to save so you’ll notice that we get an error in the console it says cannot set properties of null setting text content so what it’s saying is that this is null and the reason for that is when we put our script tag in the head like this where we’re do we’re running our JavaScript before the page is loaded and before the Dom is loaded so it doesn’t know what this is yet so a common practice would be to use the load event so we could say on window we could say dot add actually I’ll show you the the on load which was what we saw a lot of back then so window dot on load and this was kind of a hack to do window on load set it to function and then put our code in there so you’ll see if I save now the H1 is replaced and we don’t get an error anymore so by using on load we’re waiting for the entire page to load and that includes resources like images and stuff like that and of course we could use add event listener which wasn’t around back then what I’m talking about but you can use this with load as well so we’ll just put a function in here and let’s just copy that and paste that in I’ll comment that out and you’ll see that just get rid of that semicolon that does the same thing now there’s also an event called Dom content loaded so what I’m going to do is copy this and then paste it in I’m going to change load to Dom all caps and then content loaded and then I’ll save and we get the same result now the difference between load and Dom content loaded is load waits for the the entire page to load including all resources such as images where Dom content loaded runs as soon as the Dom is parsed and loaded so if I were to run both of these let’s actually you know what we’ll do is uh let’s just replace this with a console log so I’m going to say console log and we’ll say page loaded and then I’m going to replace this one with a console log and we’ll say here Dom uh what happened here let’s say Dom loaded and notice that the Dom gets loaded first obviously because the page load includes the Dom and everything else any obviously there’s no images here but any other resources that need to be loaded now if I were to do a console log in the global scope down here and we’ll just say run me if I save that that gets run before either of these because we’re not in any of these events where we’re waiting for the page to load which is fine when the script is down you know under the page down above the ending body tag but if you have to access any Dom elements from the global scope then you’re going to get an error if the script tag is in the head now the exception to this is if you use the fairly new defer attribute so if I come to the script that’s in the head here and then I add on to it defer like that and I save and then let’s come over here and we’ll take I will not take let’s just go in back into the global scope here and say document and we’ll select the H1 and then let’s set the inner text and set that to hello world and if I save that you’ll notice that it works okay so I’m not getting the error even though my script is in the head but I use this defer attribute which basically will do just that it will defer the JavaScript code from running until it can run until the pages are the Dom is loaded so this is this is pretty new I don’t know when exactly this was available but if you want to do it this way and put your scripts in the head that’s absolutely fine just make sure you use defer I still prefer to keep my my scripts down above the ending body tag but from this point on if you want to use defer and put them in the head that’s fine now there’s just a couple other events that I want to show you that we can use on the windows so let’s say window dot add event listener and we can listen for a resize okay so there’s a resize event and what I’m going to do here is I’m gonna actually take this and move this into here but I’m going to set the the text to show the size of the window so we’ll put some backticks in here and we’ll say resized resized two and we can remember we can get the inner width and the inner height on the window object so let’s say window Dot in our width and then we’ll also put the window Dot inner height so I’m going to save that and now if I resize it’s going to change the H1 to show the the inner width and inner height and you’ll see it’s just it keeps changing because that event just fires off every time the browser is resized also it stayed at 276 because we didn’t change the height if I move this console then that’s going to change the height also listen for a scroll event so this can be helpful for certain UI effects that you want to create so I’m going to add an event listener onto the window and I’m going to listen for scroll and of course you could do window dot on scroll equals a function if you want to do it like that and then let’s create a function and what I’m going to do is console log and we’ll use some back ticks and we’ll say scrolled and let’s add in here because on the window object we have access to scroll X which is the position when you’re you know scrolling horizontal and then we also have the um scroll y so window Dot scroll Y and now if I scroll down you’ll see the the x is going to stay at zero because I’m not scrolling horizontal at all but the more I scroll down you’ll see the higher that that scroll X I’m sorry scroll y value gets and we could do some cool stuff here like if you have a navigation bar at the top and you want to have it be like translucent or something when you start to scroll you can just test where that scroll y value is so in fact we could do something like this we could say if the window Dot scroll Y is let’s say greater than 70. then let’s take the document body and on the style we’ll take the color or let’s do background so background color and we’ll set that to Black and then we’ll set the color to white the text color change that to color all right if I do that and then I start to scroll as soon as it hits 70 the background turns black now it’s going to stay black because I didn’t specify anything else but I could put an else on here and then we could take this and then just change this back to White and change the text Back to Black so now if I come down I hit 70 it turns black I go back up it turns White so this is the start of learning how to create really cool Dynamic functionality or dynamic effects within your UI so what else we also have focus in blur and just to give you a quick example of that we’ll say window dot add event listener and just like you have on inputs we focus in blur it’s just when you click in and when you click out so let’s just mess around with this for a second and let’s take document Dot query selector and we’ll select the paragraph actually let’s select all paragraphs so we’ll say all and then let’s look through those so we’ll say four each P so for each paragraph then let’s say p dot Style dot color and set that to Blue and then let’s put one for blur so on blur which is when you click out of the window then we’ll set it to bla Back to Black so now if I click in here you can see the scroll thing’s still working too but you can see that they’re all it’s all blue if I click outside of the window so anywhere else then it turns black Back to Black and there’s other events on the window object as well if you want to check the mdn docs of course you can do that but yeah so that those are window events and also the the page loading events

By Amjad Izhar
Contact: amjad.izhar@gmail.com
https://amjadizhar.blog


Discover more from Amjad Izhar Blog

Subscribe to get the latest posts sent to your email.

Comments

Leave a comment