This collection of text appears to be a script or transcript from a beginner’s JavaScript course or tutorial. It starts with an introduction to the instructor and the purpose of the revised course, acknowledging the rapid changes in JavaScript. The content then transitions into fundamental programming concepts, covering variables, data types, operators, control flow (decisions and iteration), functions, and scope. More advanced topics such as objects, prototypes, classes, arrow functions, and truthy/falsy values are introduced, along with practical applications like string and array methods, error handling with try-catch, and working with the Document Object Model (DOM) in web browsers. The text concludes with a brief discussion of popular JavaScript libraries and frameworks for both client-side and server-side development.
Based on the sources provided, here is a discussion of Javascript programming:
This material provides an introduction to Javascript programming, primarily aimed at absolute beginners to Javascript and programming in general. It assumes some familiarity with HTML and CSS, but is designed so that beginners to programming can follow along. The focus is on teaching the pure Javascript language first. The course initially uses console or command-line style applications to isolate the language itself without getting clouded by HTML and CSS. The application of Javascript in the context of the web browser and the Document Object Model (DOM) is discussed later in the course.
Javascript is described as a highly dynamic, unique, and sometimes quirky language. The community around Javascript is moving extremely quickly. It is the most popular programming language not just in the web browser, where there are hundreds of frameworks and libraries available, but also increasingly popular for server-side web development using frameworks like Node.js. It can also be used in other environments, such as writing video games in Unity.
As software developers, the job is to author code using a language that is human-readable and can be understood, parsed, interpreted, and ultimately executed by a computer. Code is saved into files, and an execution environment, such as a web browser or Node.js, interprets and executes it. Javascript has a syntax, similar to English, with rules for proper versus incorrect syntax. It has “parts of speech,” vocabulary words, and structures like statements which are complete instructions.
Key concepts discussed include:
Statements and Expressions: A statement is a complete instruction, like a sentence. A Javascript file contains one or more statements executed sequentially. Statements are made up of one or more expressions. An expression is made up of operators and operands.
Operators and Operands: Operators are things like keywords and symbols (e.g., let, +, =, ++, –, %, ., &&, ||, () for function invocation, {} for code blocks). Operands are things like identifiers (variable names) and functions. Programmers give operands their names. Combining operators and operands creates expressions used to compose statements.
Variables and Data Types: Variables are like containers or buckets that can hold values. Values, not variables, have data types. Basic data types include number, boolean, and string. Other types mentioned are undefined (for declared but unassigned variables), null, and symbol (new in the latest version). Objects are another data type.
Variable Declaration: Variables can be declared using keywords.
var: The original keyword, still seen frequently, but its usage is nuanced and can have unexpected ramifications related to scope.
let: The recommended keyword for declaring variables whose values may change. It works more like variable declaration in many other programming languages.
const: Used to declare variables whose values are not intended to change. Attempting to reassign a value to a const variable results in an error.
Coercion: Javascript attempts to implicitly convert values from one data type to another in certain operations (e.g., adding a number and a string may result in the number being coerced into a string and concatenated). Explicit conversion is also possible using functions like parseInt.
Functions: A function is a named block of reusable code that can be called by its name. Functions are primary constructs in Javascript for getting things done.
Function Declarations: Created with the function keyword, typically given a name.
Function Expressions: Anonymous functions (without a name) that can be assigned to variables or passed as arguments to other functions.
Immediately Invoked Function Expressions (IIFE): A function expression that is defined and executed immediately. This is a common pattern, especially for managing scope.
Decision Statements: Allow different blocks of code to execute based on conditions.
if: Executes code if a specified expression evaluates to true. Can include else and else if.
switch: Evaluates an expression and executes code based on matching cases.
Ternary Operator: A shorthand for simple if/else logic.
Iteration Statements (Loops): Allow a block of code to be executed multiple times until a condition is met.
for loop: Has three parts: initialization, condition, and increment/decrement. Often used to iterate over arrays using the array’s length property.
while loop: Executes a block of code as long as a specified condition is true.
forEach: A method available on arrays and other iterables that executes a provided function once for each array element.
Scope: Refers to the lifespan and accessibility of variables. Variables are removed from memory when they go out of scope. Code blocks (like those in functions or loops) define scope. Defining variables and functions in the global scope (global namespace) is particularly dangerous, especially in a web browser, because these variables remain in memory until the page navigates away and can lead to naming conflicts. Techniques like IIFEs and modules help reduce impact on the global namespace.
Objects: Objects are another data type. They can represent tangible things (like a car) or abstract concepts. Objects have properties (values associated with them) and methods (functions associated with them). Properties and methods are accessed using dot notation (e.g., object.property, object.method()). Objects can be nested. Object literals (creating objects using {}) look similar to JSON (Javascript Object Notation), which is a popular data format.
this Keyword: This keyword represents the context in which a function is called. Its meaning depends on how the function is invoked, which can be confusing, especially for those coming from other programming languages where this might behave differently. In the global scope in Node, this might refer to the global object. In a web browser context, how this is bound depends on how the function is called.
Primitives vs. Built-ins (Natives): Javascript has primitive types (string, number, boolean, etc.) and corresponding built-in “native” functions (like String, Number, Boolean) that return objects. When you perform operations on primitives (like calling a method on a string literal), the Javascript compiler temporarily “boxes” the primitive into its native object equivalent to provide access to rich functionality (methods).
Constructor Functions: Functions that are intended to be called using the new keyword. When called with new, they return a new object.
Classes and Prototypes: Javascript does not have classes or traditional object-oriented inheritance in the same way as languages like C# or Java. Javascript is object-based; you can create objects and dynamically add properties and methods. Instead of traditional inheritance, Javascript uses a prototype chain. When you create a new object based on an existing one, a permanent link is created between the new object and its prototype (the original object). If you try to access a property on the new object, and it doesn’t exist directly on that object, Javascript looks up the prototype chain. Some call this “prototypal inheritance” or “objects linking to other objects”. The class keyword was added in a newer version of Javascript as “syntactic sugar” to make it feel more familiar to developers from traditional OOP languages, but it still uses the underlying object and prototype model.
Arrow Functions: A shorthand syntax for defining functions, introduced in a recent version of Javascript. They are frequently used.
Truthy and Falsey: Concepts specific to Javascript evaluation. Some values or expressions that are not strictly true or false are considered “truthy” or “falsey” when evaluated in a boolean context (like an if statement condition). Examples of falsey values include null, undefined, NaN, 0, and empty strings. Non-zero numbers and non-empty strings are truthy.
Common Methods: Many useful methods are available on built-in native objects like String and Array. Examples mentioned include split, repeat, trim, and join for strings and push, pop, shift, forEach, and every for arrays.
Error Handling: Javascript’s compiler is often lenient, but when it encounters something it cannot process, it throws an error or exception. Information about the error is captured in an Error object. The try…catch…finally construct allows developers to safeguard code that might throw exceptions and handle them gracefully.
When discussing Javascript in a web browser, the course introduces the Document Object Model (DOM). The web browser parses HTML, CSS, and Javascript to build an object graph representing the document and its elements. The DOM is an API (Application Programming Interface) that allows Javascript to interact with these elements (referred to as nodes), modify their properties and attributes, add or remove nodes, and associate functions with events triggered by the user (like clicks or mouseovers).
Different ways to include Javascript in an HTML page are shown:
Inline Javascript: Writing code directly within HTML attributes like onclick. This is generally frowned upon professionally.
<script> tag: Including Javascript code within <script> tags in the HTML document. Placing script tags at the bottom of the <body> is often recommended so the HTML can load first. Defining functions within <script> tags can then be referenced by inline handlers. This approach is also often professionally discouraged.
External Javascript file: Keeping Javascript in a separate .js file and linking to it using the src attribute of a <script> tag. This is the generally preferred professional approach for separating concerns. Event handlers are then programmatically attached to DOM elements in the Javascript file using methods like addEventListener after getting a reference to the element (e.g., using document.getElementById).
After establishing a foundation, a learner might move on to more advanced Javascript topics and explore modern client-side frameworks (like React or Vue.js) and server-side frameworks (like Node.js and Express.js). Learning is iterative, and revisiting concepts is normal, even for experienced developers.
JavaScript vs. Traditional OOP
Based on the provided sources, let’s discuss Object-oriented programming (OOP) in the context of Javascript.
Object-oriented programming is a significant concept among software developers. In some of the most popular programming languages, such as C#, Java, and C++, you create objects using a construct called a class. A class is essentially a pattern or blueprint from which you create individual instances of objects. With traditional OOP classes, you define properties and methods upfront in the class definition. These are typically static and cannot be changed over the lifetime of the objects created from that class.
Traditional OOP also includes the concept of inheritance. This allows you to create specialized versions of a class (child class) that borrow or inherit all the properties and methods from a parent class. The child class can then be extended by adding its own unique properties and methods, making it a more specialized version of the parent. In this model, you create a class hierarchy where one class inherits from another. The focus in these languages is on the relationship between classes.
Javascript’s approach to creating and relating objects is different from traditional OOP languages. Javascript is primarily object-based. You can create an object and then dynamically add properties and methods to it whenever needed.
Instead of traditional class inheritance, Javascript uses a concept called the prototype chain. When you create a new object based on an existing object (which serves as the prototype), a permanent link is created between the new object and its prototype. If you try to access a property or method on the new object that doesn’t exist directly on it, Javascript automatically looks up the prototype chain to see if it exists on the prototype object. This is often referred to as “prototypal inheritance”, but some prefer the term “objects linking to other objects” (OLOO) as a more accurate description. The key distinction is that Javascript’s focus is on the relationship between individual objects and how they are chained together, rather than a static hierarchy between classes.
A recent version of Javascript introduced the class keyword. This keyword provides a syntax that resembles traditional OOP classes, but it is described as “syntactic sugar” on top of the existing Javascript object and prototype models. It does not fundamentally change how Javascript works. The class keyword was added to help developers transitioning from traditional OOP languages like C# or Java feel more familiar with Javascript’s dynamic object-based model. Even when using the class and extends keywords (which allow for approximating inheritance in Javascript’s class syntax), the underlying mechanism still relies on the prototype chain. Javascript purists sometimes point out that the class feature can be misleading because developers still need to understand the underlying prototype model to fully grasp Javascript’s object system.
For developers coming from traditional OOP environments who need to be productive quickly and desire a feel closer to languages like C# or Java, Typescript is mentioned as an alternative. Typescript is a superset of Javascript that adds features like static typing and a class/inheritance model more aligned with traditional OOP, and it is then transpiled into pure Javascript.
In summary, while Javascript has adopted keywords like class and extends to provide a syntax familiar to traditional OOP developers, its core mechanism for object creation, relationships, and code reuse is based on a dynamic, object-based model and the prototype chain, rather than the class-based inheritance found in many other languages.
JavaScript DOM Manipulation and Best Practices
Drawing on the sources, let’s discuss Document Object Model (DOM) manipulation in the context of JavaScript and web browsers.
The Document Object Model (DOM) is an object-based representation of the HTML elements in a web page. A web browser constructs this model in memory by parsing the downloaded HTML. This object graph or tree represents all the elements, their attributes, text values, and the relationships between them, such as elements containing other elements (e.g., a div containing a paragraph or list items). Each part of this structure is referred to as a node, including the document itself, elements, attributes, and text.
JavaScript plays a crucial role in interacting with the web page by using the DOM. The DOM provides a rich API (a collection of methods and properties) that allows developers to programmatically access and manipulate these nodes.
Using the DOM API, you can perform various manipulations:
Access nodes: Find a specific node or a collection of nodes based on criteria like their ID.
Modify nodes: Change the text content of a node.
Change attributes and styles: Modify attributes of a node, such as its class or inline styles. The style attribute itself is an object with properties corresponding to CSS styles that can be programmatically changed.
Add new nodes: Dynamically create new elements or text nodes and append them to existing nodes in the document tree.
Remove nodes: Remove existing nodes from the document tree.
Handle events: Associate your JavaScript functions with events raised by the web browser, typically triggered by user interactions like clicks, hovers, or keyboard input.
When writing JavaScript for web pages, the sources discuss different techniques. While you might see examples where JavaScript is written directly into HTML attributes (like onclick) or within <script> tags embedded directly in the HTML, this approach is generally frowned upon professionally. The recommended practice is to follow the principle of separation of concerns and keep your JavaScript code in separate .js files.
Within an external JavaScript file, the typical pattern for DOM manipulation involves:
Often wrapping your code in an Immediately Invoked Function Expression (IIFE) to prevent polluting the global namespace.
Getting a programmatic reference to the desired DOM elements using methods provided by the DOM API, such as document.getElementById().
Attaching event listeners to those elements using methods like addEventListener(), specifying the event type (e.g., ‘click’) and the function that should be called when the event occurs. This function is the event handler.
Inside event handlers or other functions, using the acquired references to manipulate the properties (like innerText, style, classList) or methods (like appendChild, removeChild) of the DOM nodes.
The sources provide a practical example demonstrating these techniques, showing how to get a reference to a button, attach a click handler using addEventListener, and then within the handler, manipulate other DOM elements by changing their text, size, color, and dynamically creating and updating a list of colored divs. This illustrates how to make web pages dynamic and interactive. The possibilities for DOM manipulation are extensive, limited primarily by what you can imagine and the available API methods. Building complex interactions often involves working incrementally, getting small parts working before moving on to the next.
It’s important to note that the DOM nodes you work with in a web browser environment should not be confused with the Node.js runtime environment. They are completely different concepts.
Javascript Functions and Scope Fundamentals
Based on the provided sources and our conversation history, let’s discuss Functions and scope in Javascript.
Functions are a fundamental concept in Javascript. In their simplest form, a function is merely a block of code that you, as a programmer, can name. Once named, this block of code can be called by its name. The primary reason for using functions is to have code that you want to reuse throughout your application. Instead of writing the same lines of code multiple times, you put them into a function block and can execute that block repeatedly by calling the function’s name. Functions are one of the primary constructs in Javascript for getting things done.
There are several ways to define functions in Javascript. The sources discuss function declarations and function expressions. A function declaration uses the function keyword followed by an identifier (the function name). A function expression assigns a function (often without a name) to a variable. You can assign a function to a variable, and then invoke the function using that variable name with the function invocation operator.
Functions can accept input parameters or arguments, which allow you to pass information into the function when you call it. These parameters are defined within the parentheses after the function name (or the function keyword in an expression). You can use these parameter names as variables within the function’s body.
Functions can also return values. While some functions may simply perform actions and exit quietly, others perform an operation and give a value back to the caller using the return keyword. A function can return one value. The result of a function call that returns a value is an expression that can be used like any other value, for example, assigned to a variable.
Javascript functions can do much more than just house reusable code. They can be used as input parameters to other functions. An example provided is using a function expression as the “handler” argument for the setTimeout function. Functions are also their own data type, alongside string, number, boolean, object, and undefined.
A shortened syntax for writing functions was introduced in a later version of Javascript: arrow functions. Arrow functions remove the need for the function keyword and use a “fat arrow” (=>) to point to the function body. They can accept input parameters within parentheses before the arrow and are often used in situations where a concise function is needed, such as with array methods like map, filter, or forEach.
Functions defined inside an object are typically referred to as methods. Using the dot operator (member access operator), you can access these methods on the object.
The way a function is called can really change its meaning and intended use, sometimes even changing the functionality defined inside it. This is particularly relevant when considering the this keyword. The value of the this keyword inside a function depends on how the function is called or invoked. For instance, if a function is called in the global context, this refers to the global object (window in browsers, global in Node.js). If called as a method of an object, this refers to that object. Methods like call and apply allow you to explicitly set what the this keyword should represent within a function call.
Scope is another crucial concept in Javascript. Variables in Javascript have a lifespan and a sort of “citizenship”. This means they are “born” (declared), can be used, and then “die” (removed from memory) when they go out of scope. Scope determines where variables are available within your application.
The rules of scope are based on code blocks. A variable declared in an outermost scope will have its life and citizenship in all inner scopes contained within it. This means variables declared outside a function (in the “outer” scope) can be referenced inside that function (in the “inner” scope). However, if a variable is defined in an innermost scope (like inside a function or an if block), it will not be available to outer scopes. Attempting to access a variable outside of its defined scope will result in an error.
The global scope is the topmost level of scope. Declaring variables at the global scope, especially when writing Javascript for a web browser, is generally considered a bad idea and is often referred to as a “crucial concern”. The primary danger of using the global scope is naming collisions. When multiple scripts or parts of your application define variables or functions with the same name in the global scope, they can overwrite each other, leading to unexpected behavior or errors.
To address the dangers of global scope, newer features like the let keyword are recommended over var, as var can attach variables to the global scope (like the window object in a web browser). Furthermore, professional developers often use design patterns and techniques to avoid writing code in the global scope. One such technique is the Immediately Invoked Function Expression (IIFE). An IIFE is a function expression that is immediately executed, creating its own scope and preventing variables declared inside it from polluting the global namespace.
A related design pattern that leverages IIFEs and returning objects is the Module Pattern (and its variation, the Revealing Module Pattern). This pattern uses an IIFE to create a function that returns an object. Variables and functions defined inside the IIFE but not returned in the object are essentially private to that scope, while those returned in the object become public members accessible through the single variable assigned to the returned object. This approach reduces the number of variables in the global scope and provides a form of encapsulation.
The interaction between functions and scope gives rise to the concept of closures. A closure allows you to associate some data with a function and use the function with that data “baked into it”. It happens when a function is defined inside another function, and the inner function “remembers” or retains access to variables and input parameters from the outer function’s scope (its lexical environment) even after the outer function has finished executing. The term lexical scope refers to the fact that scope in Javascript is determined by where variables are declared in the source code. Nested functions have access to variables declared in their containing (outer) scopes. Each closure created gets its own lexical environment, meaning it has its own set of variables from the outer scope that it retains access to. Closures are a powerful feature that relies on how scoping works in Javascript.
Javascript Data Types and Coercion
Drawing on the sources and our conversation history, let’s discuss data types in Javascript.
In Javascript, a data type is essentially a description of the kind of data that you want to store and what you intend to do with that data. It’s important to note that values, not variables, have a data type. This is one of the things that makes Javascript unique when compared to other programming languages.
The sources discuss several data types that we work with:
Number: Used if you want to perform math or some algebraic operation. It can be any positive or negative number, including decimal values.
Boolean: Used if you want to do a yes or no, true or false evaluation. The only two possible values are true or false.
String: A shorthand for “string of characters” and usually represented with single quotes. Anything inside the single quotes is a literal string of characters.
Undefined: Represents a variable that was declared but has had nothing assigned to it. The value is undefined, and the type is undefined. This means Javascript was expecting to have a value set, but one was never set.
Function: Functions are their own data type.
Object: While an array isn’t a data type of itself, it is a type of something called object. Objects are different from arrays; an array holds a list of information (many data items), while an object contains the related properties of a single data element. Objects can contain properties where the values can be any data type, including other arrays or objects. Regular expressions are also a special built-in object to Javascript. The DOM itself is an object-based representation of HTML elements.
Null: This primitive data type represents a variable where an object reference was expected but is not set to any object reference. It is not zero, not undefined, and not an empty string. It’s different from undefined because with null, you were expecting an object reference, whereas with undefined, you were expecting perhaps a number, string, or boolean.
Symbol: Mentioned as a new data type in the latest version of Javascript that won’t be discussed in detail in this course.
The sources also discuss the concept of coercion, which is when Javascript implicitly attempts to convert one data type into another. This can happen, for example, when using the + operator with a number and a string; Javascript might coerce the number into a string and perform concatenation instead of addition. While some consider this “evil” or “dangerous,” it’s just part of the language. You can also explicitly force conversion using built-in functions like parseInt() to convert a string representation of an integer into a numeric value.
Furthermore, the primitive types like string, boolean, and number have corresponding built-ins or natives. These are functions that return objects with additional methods and properties. Behind the scenes, the Javascript compiler will wrap or “box” a primitive type into its built-in native equivalent object when you try to call a method on it, providing rich functionality like .toLowerCase() on a string. These built-in native functions often have the same name as their primitive counterparts but start with an uppercase letter (e.g., String, Number, Boolean). You can explicitly create an object from a built-in native using the new keyword. To get the primitive value back out of one of these native objects, you can use the .valueOf() method. Arrays and regular expressions also have built-in natives that provide extra functionality, even though their primitive version might be considered object.
The typeof operator can be used to determine the data type of a value. For instance, applying typeof to a variable holding a number will output “number”, a boolean “boolean”, a string “string”, an undefined variable “undefined”, a function “function”, and an array or regular expression “object”.
Understanding data types and how Javascript handles them, including coercion and built-in natives, is crucial for predicting how your code will behave.
Javascript tutorial for beginners Full course | javascript Full crash course for Beginners
Affiliate Disclosure: This blog may contain affiliate links, which means I may earn a small commission if you click on the link and make a purchase. This comes at no additional cost to you. I only recommend products or services that I believe will add value to my readers. Your support helps keep this blog running and allows me to continue providing you with quality content. Thank you for your support!
This tutorial serves as a guide for JavaScript beginners, aiming to impart foundational knowledge for creating dynamic web pages and applications. It begins with an introduction to JavaScript’s core concepts, including its syntax, how to enable it in browsers, and where to place code within HTML. The text then progresses to cover essential programming elements such as variables, data types, operators, control flow statements (like if-else and loops), and functions. Furthermore, the tutorial explores JavaScript objects, including built-in types like Number, String, and Array, as well as concepts like events and browser interactions. Finally, it touches upon more advanced topics such as error handling, form validation, and debugging, providing a comprehensive overview for newcomers to the language.
What are two key characteristics of JavaScript as a programming language, and for what primary purpose was it designed?
Explain the concept of client-side JavaScript and provide one advantage it offers over traditional server-side scripting.
Describe two limitations of client-side JavaScript that prevent it from being considered a full-fledged general-purpose programming language.
What are the standard HTML tags used to embed JavaScript code within a web page, and what are the recommended values for their key attributes?
Explain the significance of the var keyword in JavaScript and describe the difference between declaring and initializing a variable.
What are the two primary scopes of variables in JavaScript, and how does JavaScript handle variable names that exist in both scopes within a function?
Provide three examples of arithmetic operators in JavaScript and briefly explain their function.
Describe the purpose of comparison operators in JavaScript and give an example of a comparison that would evaluate to false if variable x holds the value 5 and variable y holds the value 10.
Explain the functionality of the logical AND (&&) operator in JavaScript. Under what condition will an expression using this operator evaluate to true?
What is the purpose of JavaScript events, and can you provide an example of a common HTML event and how it might be used with JavaScript?
Quiz Answer Key
JavaScript is a lightweight, interpreted programming language. It was primarily designed for creating network-centric applications and enhancing web pages with dynamic and interactive elements.
Client-side JavaScript is JavaScript code that is executed by the user’s web browser, rather than on a web server. One advantage is less server interaction, as user input can be validated in the browser before being sent to the server.
Two limitations of client-side JavaScript are its inability to read or write files (for security reasons) and its lack of built-in support for networking applications or multithreading/multiprocessing.
The standard HTML tags for embedding JavaScript are <script> and </script>. The recommended attribute to specify the scripting language is type with the value “text/javascript”. The language attribute is considered phased out in recent HTML versions.
The var keyword is used to declare variables in JavaScript, essentially creating a named container in memory. Declaration is simply stating the variable name (e.g., var myVariable;), while initialization is assigning an initial value to the variable (e.g., var myVariable = 10;).
The two primary scopes are global scope (variables defined anywhere in the code) and local scope (variables defined within a function). Within a function, a local variable with the same name as a global variable takes precedence, effectively hiding the global variable.
Examples of arithmetic operators include + (addition), – (subtraction), and * (multiplication). The addition operator adds two operands, the subtraction operator subtracts the second operand from the first, and the multiplication operator multiplies both operands.
Comparison operators in JavaScript are used to compare the values of two operands and return a Boolean value (true or false) based on the comparison. For example, (x > y) where x is 5 and y is 10 would evaluate to false.
The logical AND (&&) operator evaluates to true only if both of its operands (the expressions on either side of the operator) evaluate to true. If either operand is false, the entire expression will be false.
JavaScript events are actions or occurrences that happen in the browser, such as a user clicking a button or a page finishing loading. A common HTML event is onclick, which can be used to execute a JavaScript function when a user clicks on an HTML element.
Essay Format Questions
Discuss the advantages and limitations of using JavaScript for web development, considering its client-side nature and its integration with HTML. How has the evolution of web technologies addressed some of these limitations?
Explain the significance of variable scope in JavaScript, differentiating between global and local variables. Provide scenarios where understanding variable scope is crucial for avoiding errors and maintaining code functionality.
Compare and contrast the different types of operators available in JavaScript (arithmetic, comparison, logical, assignment). Provide examples of how each type of operator contributes to the functionality of a JavaScript program.
Describe the different ways JavaScript code can be placed within an HTML document, including the advantages and potential disadvantages of each method. When might you choose one placement method over another?
Discuss the fundamental data types supported by JavaScript. How does JavaScript’s handling of data types differ from strictly typed languages, and what are the implications of this dynamic typing?
Glossary of Key Terms
Interpreted Language: A programming language where the code is executed line by line by an interpreter, without the need for prior compilation into machine code.
Client-Side Scripting: Code that is executed by the user’s web browser, as opposed to being run on a web server.
Syntax: The set of rules that define the structure of a programming language, including how statements are written and organized.
Variable: A named storage location in a computer’s memory that can hold a value.
Declaration: The act of introducing a variable name to the program, indicating that a storage location will be used for that name.
Initialization: The act of assigning an initial value to a variable at the time of its creation or later in the program.
Scope: The region of a program where a particular variable can be accessed.
Global Variable: A variable that is declared outside of any function and can be accessed from any part of the JavaScript code.
Local Variable: A variable that is declared inside a function and can only be accessed within that function.
Operator: A symbol or keyword that performs an operation on one or more operands (values or variables).
Operand: A value or variable that an operator acts upon.
Arithmetic Operator: A symbol that performs mathematical calculations (e.g., addition, subtraction, multiplication).
Comparison Operator: A symbol that compares two operands and returns a Boolean value based on the relationship between them (e.g., equal to, greater than).
Logical Operator: A symbol that performs Boolean logic operations on one or more Boolean operands (e.g., AND, OR, NOT).
Assignment Operator: A symbol that assigns a value to a variable (e.g., =, +=).
Event: An action or occurrence that happens in the browser, such as a user interaction (e.g., clicking a button) or a browser process (e.g., page loading).
JavaScript Tutorial Briefing Document
Date: October 26, 2023 Source: Excerpts from “javascript_tutorial.pdf” (Tutorials Point, Copyright 2015)
Overview:
This document provides a briefing on the fundamental concepts of JavaScript as presented in the initial sections of the “javascript_tutorial.pdf”. The tutorial is designed for beginners with prior knowledge of HTML and some exposure to object-oriented programming and online application creation. It covers the basics of the language, including its nature, syntax, how to enable it in browsers, placement within HTML, fundamental data types, variables, operators, control flow statements (if-else, switch-case, loops), functions, events, cookies, page redirection, dialog boxes, the void keyword, and page printing. The document also introduces JavaScript objects and their basic properties and methods, including built-in objects like Number, Boolean, String, Array, Date, Math, and RegExp, as well as the Document Object Model (DOM). Finally, it touches upon advanced topics like errors and exceptions, form validation, animation, multimedia, debugging, image maps, and browser-specific information.
Part 1: JavaScript Basics
This section lays the groundwork for understanding JavaScript.
What is JavaScript? JavaScript is described as a “lightweight, interpreted programming language” primarily used for creating “network-centric applications” and adding interactivity to web pages. It is highlighted as “complimentary to and integrated with Java” and “HTML“, as well as being “open and cross-platform.” Its history is briefly mentioned, noting its initial name as LiveScript and its introduction in Netscape 2.0 in 1995. The importance of the ECMA-262 Specification for standardizing the core language is also noted.
Client-Side JavaScript: The tutorial emphasizes that client-side JavaScript, embedded in or referenced by HTML documents, is the most common form. It allows web pages to be dynamic, interact with users, control browsers, and dynamically create HTML content. Advantages over server-side scripts include “less server interaction“, “immediate feedback to the visitors“, “increased interactivity“, and “richer interfaces.” Limitations include the inability to read or write files (for security), lack of networking application support, and no multithreading or multiprocessor capabilities.
JavaScript Development Tools: The tutorial points out that JavaScript doesn’t require expensive tools, with a simple text editor being sufficient. Several more advanced editors like Microsoft FrontPage, Macromedia Dreamweaver MX, and Macromedia HomeSite 5 are also mentioned.
Where is JavaScript Today? The tutorial mentions ECMAScript Edition 5 as a significant update and notes that JavaScript 2.0 conforms to this standard with minor differences. It states that Netscape’s JavaScript and Microsoft’s JScript align with the ECMAScript standard while still supporting non-standard features.
JavaScript Syntax: JavaScript code is placed within <script>…</script> HTML tags. The <script> tag can be placed anywhere but is “normally recommended” within the <head> tags. Important attributes of the <script> tag are language (though phased out, typically “javascript”) and type (recommended, set to “text/javascript”). A basic “Hello World” example using document.write() is provided, along with the use of HTML comments (<!– … //–>) to handle browsers without JavaScript support, where // within the comment prevents the closing HTML comment tag from being interpreted as JavaScript. The tutorial clarifies that “JavaScript ignores spaces, tabs, and newlines” and that “Semicolons are Optional” if statements are on separate lines, although using them is good practice. Importantly, “JavaScript is a case-sensitive language.” Both // (single-line) and /* … */ (multi-line) comments are supported, and <!– is treated as a single-line JavaScript comment, with //–> being the recommended way to close an HTML comment containing JavaScript.
JavaScript Enabling: The tutorial provides step-by-step instructions on how to enable or disable JavaScript in various popular browsers: Internet Explorer, Firefox, Chrome, and Opera. The use of <noscript> tags to display a warning message to users with JavaScript disabled is also explained. For example:
<noscript>
Sorry…JavaScript is needed to go ahead.
</noscript>
JavaScript Placement: The tutorial details four ways to include JavaScript in HTML: within the <head>, within the <body>, in both <head> and <body>, and in an external .js file included using the src attribute of the <script> tag. Placing scripts in the <head> is suggested for scripts that run on events, while placing them in the <body> is for scripts that generate content on page load. External files (<script type=”text/javascript” src=”filename.js” ></script>) are recommended for reusing identical JavaScript code across multiple pages.
JavaScript Variables: JavaScript supports three primitive data types: “Numbers, e.g., 123, 120.50 etc.“, “Strings of text, e.g. ‘This text string’ etc.“, and “Boolean, e.g. true or false.“. It also defines trivial types null and undefined, and a composite type object. All numbers are treated as 64-bit floating-point values. Variables are declared using the var keyword (var money;, var money, name;). Initialization can occur at declaration or later (var name = “Ali”;, money = 2000.50;). Re-declaration of variables with the same name using var should be avoided. JavaScript is an “untyped language“, meaning a variable can hold any data type, and the type can change during execution. Variable scope is either global (defined anywhere) or local (visible only within a function). Local variables take precedence over global variables with the same name within a function. Rules for variable names include: no JavaScript reserved keywords, must not start with a numeral, must begin with a letter or underscore, and are case-sensitive. A comprehensive list of JavaScript reserved words is provided.
JavaScript Operators: An operator is defined as a symbol that performs an operation on operands (e.g., in 4 + 5 = 9, + is the operator, and 4 and 5 are operands). The tutorial covers arithmetic operators (+, -, *, /, %, ++, –, noting that + can also concatenate strings), comparison operators (==, !=, >, <, >=, <=), logical operators (&&, ||, !), bitwise operators (&, |, ^, ~, <<, >>, >>>), assignment operators (=, +=, -=, *=, /=, %=, and their bitwise counterparts), and miscellaneous operators, specifically the conditional (ternary) operator (? 🙂 and the typeof operator. The typeof operator returns a string indicating the data type of its operand (e.g., “number”, “string”, “boolean”, “object”, “function”, “undefined”). Examples are provided for each operator type. For instance, regarding the conditional operator:
result = (a > b) ? 100 : 200;
This assigns 100 to result if a is greater than b, and 200 otherwise.
Part 2: JavaScript Objects
This section introduces the concept of objects in JavaScript.
JavaScript Objects: An object is a collection of properties (named values) and methods (functions that can be performed on the object). The tutorial covers user-defined objects, defining methods for objects, and the use of the with keyword (though often discouraged).
Built-in Objects: The tutorial then delves into various built-in JavaScript objects, detailing their properties and methods with examples:
Number: Properties like MAX_VALUE, MIN_VALUE, NaN, NEGATIVE_INFINITY, POSITIVE_INFINITY, prototype, constructor, and methods like toExponential(), toFixed(), toLocaleString(), toPrecision(), toString(), valueOf().
Boolean: Properties constructor, prototype, and methods toSource(), toString(), valueOf().
String: Properties constructor, length, prototype, and numerous methods for string manipulation (e.g., charAt(), charCodeAt(), concat(), indexOf(), lastIndexOf(), slice(), split(), replace(), search(), toLowerCase(), toUpperCase(), etc.) and HTML wrappers (e.g., anchor(), bold(), italics(), link()).
Date: Properties constructor, prototype, various methods for getting and setting date and time components (e.g., getDate(), getDay(), getFullYear(), getHours(), setDate(), setFullYear(), setHours(), getTime(), setTime(), and their UTC counterparts), as well as methods for converting dates to string formats (e.g., toDateString(), toGMTString(), toLocaleDateString(), toString(), toTimeString(), toUTCString(), valueOf()). Static methods Date.parse() and Date.UTC() are also covered.
Math: Properties for mathematical constants (e.g., Math.E, Math.PI, Math.LN2, Math.LOG2E, Math.SQRT2) and a wide range of mathematical functions as methods (e.g., abs(), acos(), asin(), atan(), ceil(), cos(), exp(), floor(), log(), max(), min(), pow(), random(), round(), sin(), sqrt(), tan()).
RegExp: Covers regular expressions, including brackets, quantifiers, literal characters, metacharacters, and modifiers. Properties like constructor, global, ignoreCase, lastIndex, multiline, source, and methods exec(), test(), toSource(), toString().
DOM (Document Object Model): Briefly introduces the DOM, mentioning “The Legacy DOM”, “The W3C DOM”, and “The IE 4 DOM”, as well as “DOM Compatibility”.
Part 3: JavaScript Advanced
This section touches upon more advanced JavaScript concepts.
Errors and Exceptions: Discusses syntax errors, runtime errors, and logical errors. It introduces the try…catch…finally statement for error handling, the throw statement for raising custom exceptions, and the onerror() method.
Form Validation: Covers basic and data format validation techniques in JavaScript to ensure user input is correct before submission.
Animation: Introduces manual and automated animation techniques using JavaScript, including rollover effects with mouse events.
Multimedia: Briefly mentions checking for browser plug-ins and controlling multimedia elements using JavaScript.
Debugging: Provides information on error messages in different browsers (IE, Firefox/Mozilla), error notifications, and general tips for debugging JavaScript code.
Image Map: Covers the implementation of image maps using JavaScript.
Browsers: Discusses the navigator object and its properties (e.g., appName, appVersion, userAgent) and methods, as well as techniques for browser detection.
Key Themes and Important Ideas:
JavaScript as a Client-Side Scripting Language: The primary role of JavaScript is to enhance HTML and create dynamic and interactive web pages by running in the user’s browser.
Ease of Implementation: JavaScript is presented as easy to start with, requiring just a text editor and a web browser.
Integration with HTML: JavaScript code is embedded within HTML using <script> tags, allowing for close interaction between the structure and behavior of a web page.
Fundamental Programming Concepts: The tutorial covers core programming concepts like variables, data types, operators, control flow statements (conditionals and loops), and functions, providing a foundation for writing more complex scripts.
Object-Oriented Capabilities: While described as interpreted, JavaScript is also highlighted as having object-oriented capabilities, with the introduction of objects, properties, and methods.
Built-in Functionality: JavaScript provides a rich set of built-in objects (Number, Boolean, String, Array, Date, Math, RegExp) with numerous properties and methods that simplify common programming tasks.
Event Handling: JavaScript enables the creation of interactive web pages by allowing scripts to respond to user-initiated events (e.g., onclick, onsubmit, onmouseover).
Browser Interaction: JavaScript can interact with the browser environment, including handling cookies, performing page redirects and refreshes, and displaying dialog boxes.
Error Handling and Validation: The tutorial introduces mechanisms for handling errors and validating user input, crucial for creating robust web applications.
Quotes:
“JavaScript is a lightweight, interpreted programming language.” (About the Tutorial, p. i)
“Designed for creating network-centric applications.” (About the Tutorial, p. i)
“It is complimentary to and integrated with Java.” (About the Tutorial, p. i)
“It is complimentary to and integrated with HTML.” (About the Tutorial, p. i)
“Client-side JavaScript is the most common form of the language. The script should be included in or referenced by an HTML document for the code to be interpreted by the browser.” (JAVASCRIPT – Overview, p. 11)
“You can place the
Understanding JavaScript Fundamentals and Web Browser Integration
What is JavaScript and what are its key characteristics?
JavaScript is a lightweight, interpreted programming language primarily designed for creating network-centric applications. It’s known for being easy to implement due to its integration with HTML, and it’s an open and cross-platform language. It allows for client-side scripting to create dynamic and interactive web pages.
Who is the intended audience for this tutorial and what prior knowledge is expected?
This tutorial is designed for JavaScript beginners who want to understand the fundamental functionalities of JavaScript to build dynamic web pages and web applications. It assumes that the reader has prior knowledge of HTML coding and some exposure to object-oriented programming concepts and creating online applications.
What are some of the advantages of using client-side JavaScript in web development?
Client-side JavaScript offers several benefits, including reduced server interaction by enabling input validation before submission, immediate feedback to users without page reloads, increased interactivity through features like mouse hover effects, and richer user interfaces with elements like drag-and-drop components.
What are some limitations of JavaScript that prevent it from being considered a full-fledged programming language?
Despite its capabilities, client-side JavaScript has limitations. For security reasons, it cannot read or write files. It also lacks built-in support for networking applications and does not have multithreading or multiprocessor capabilities.
How is JavaScript typically included and placed within an HTML document?
JavaScript code is included within HTML documents using the <script> tags. These tags can be placed in the <head>, the <body>, or both sections of the HTML. Additionally, JavaScript code can be stored in an external .js file and linked to the HTML document using the src attribute of the <script> tag. It is often recommended to place script tags in the <head> for scripts that run on events or in the <body> for scripts that generate content on page load.
What are variables in JavaScript and what are the rules for naming them?
In JavaScript, variables are named containers used to store data. Before using a variable, it must be declared using the var keyword (though modern JavaScript introduces let and const). Variable names must not be JavaScript reserved keywords, should not start with a numeral, must begin with a letter or an underscore, and are case-sensitive.
What are the different types of operators available in JavaScript and what are their basic functionalities?
JavaScript supports various types of operators, including:
Bitwise Operators: Perform operations on the binary representations of numbers (e.g., &, |, ^, ~, <<, >>, >>>).
Miscellaneous Operators: Include the conditional (ternary) operator ?: and the typeof operator to determine the data type of a variable.
How can users enable or disable JavaScript support in common web browsers like Internet Explorer, Firefox, and Chrome?
The tutorial provides step-by-step instructions for enabling and disabling JavaScript in Internet Explorer (via Internet Options > Security > Custom Level > Scripting > Active scripting), Firefox (by toggling the javascript.enabled setting in about:config), Chrome (via Settings > Show advanced settings > Content settings > Javascript), and Opera (via Tools > Preferences > Advanced > Content > Enable JavaScript). It also mentions using the <noscript> tag to display a warning to users with JavaScript disabled.
JavaScript Basics: A Beginner’s Guide
Let’s discuss JavaScript Basics based on the provided tutorial.
What is JavaScript? JavaScript is described as a lightweight, interpreted programming language. It is designed for creating network-centric applications and is commonly used as part of web pages to enable client-side scripts that can interact with the user and create dynamic pages. JavaScript has object-oriented capabilities and is complementary to and integrated with Java and HTML. It is also considered open and cross-platform and very easy to implement because it is integrated with HTML. It was initially known as LiveScript but was renamed JavaScript by Netscape, possibly due to the popularity of Java. JavaScript first appeared in Netscape 2.0 in 1995.
Audience and Prerequisites The tutorial is prepared for JavaScript beginners to help them understand the basic functionality for building dynamic web pages and web applications. It is assumed that the reader has prior knowledge of HTML coding. Some prior exposure to object-oriented programming concepts and a general idea of creating online applications would also be helpful.
Client-Side JavaScriptClient-side JavaScript is the most common form of the language. For the code to be interpreted by the browser, the script needs to be included in or referenced by an HTML document. This allows web pages to be dynamic, interacting with users, controlling the browser, and dynamically creating HTML content. Client-side JavaScript offers advantages over traditional server-side scripts, such as less server interaction, immediate feedback to visitors, increased interactivity, and richer interfaces.
Limitations of JavaScript Despite its capabilities, JavaScript is not considered a full-fledged programming language and has limitations. Client-side JavaScript does not allow reading or writing files for security reasons. It also lacks support for networking applications, multithreading, and multiprocessor capabilities. However, it excels at adding interactivity to static HTML pages.
JavaScript Development Tools A major advantage of JavaScript is that it does not require expensive development tools. You can start with a simple text editor like Notepad. As it’s an interpreted language within a web browser, a compiler is not needed. Several vendors offer more advanced JavaScript editing tools, such as Microsoft FrontPage, Macromedia Dreamweaver MX, and Macromedia HomeSite 5.
Where is JavaScript Today? Modern JavaScript implementations like Netscape’s JavaScript and Microsoft’s JScript conform to the ECMAScript standard.
Including JavaScript in HTML (Placement) JavaScript code is implemented using <script>…</script> HTML tags in a web page. These tags can be placed anywhere within the web page, but it is generally recommended to keep them within the <head> tags. The <script> tag signals the browser to interpret the text within it as a script. The <script> tag can have attributes like language (though its use is being phased out) and type, which should be set to “text/javascript”.
There are preferred ways to include JavaScript in an HTML file:
In the <head>…</head> section: This is often used for scripts that run on events, like user clicks.
In the <body>…</body> section: Scripts placed here typically run as the page loads to generate content.
In both <head> and <body> sections: You can have scripts in both sections.
In an external file: For reusing code across multiple pages, JavaScript can be stored in a .js file and included using the src attribute of the <script> tag in the <head> section.
Basic Syntax
Whitespace and Line Breaks: JavaScript ignores spaces, tabs, and newlines, allowing for flexible formatting to improve readability.
Semicolons: Semicolons at the end of simple statements are generally optional if each statement is on a separate line. However, it’s good programming practice to use semicolons.
Case Sensitivity: JavaScript is case-sensitive. Keywords, variables, function names, and identifiers must have consistent capitalization (e.g., Time and TIME are different).
Comments: JavaScript supports C-style (/* … */ for multi-line and single-line) and C++-style (// for single-line) comments. It also recognizes the HTML comment opening <!– as a single-line comment but requires the closing –> to be written as //–> to avoid being read as JavaScript code.
Enabling JavaScript in Browsers The tutorial outlines how to enable JavaScript in various browsers:
Internet Explorer: Through Tools -> Internet Options -> Security Tab -> Custom Level -> Scripting -> Active Scripting -> Enable.
Firefox: By typing about:config in the address bar, accepting the warning, searching for javascript.enabled, and toggling its value.
Chrome: Via Chrome menu -> Settings -> Show advanced settings -> Privacy -> Content settings -> Javascript and selecting the desired option.
Warning for Non-JavaScript Browsers The <noscript> tags can be used to display a warning message to users whose browsers do not support JavaScript or have it disabled. The content within <noscript> tags is displayed in place of the JavaScript code in such cases.
Variables JavaScript allows working with three primitive data types: Numbers, Strings, and Boolean. It also defines two trivial data types: null and undefined. Additionally, JavaScript supports a composite data type: object. Importantly, JavaScript does not distinguish between integer and floating-point numbers; all numbers are represented as 64-bit floating-point values according to the IEEE 754 standard.
Variables are named containers for storing data. They are declared using the var keyword. Multiple variables can be declared with a single var keyword. Variable initialization is the process of storing a value in a variable, which can happen at the time of declaration or later. The var keyword should only be used for the initial declaration or initialization of a variable. JavaScript is an untyped language, meaning a variable can hold a value of any data type, and the type can change during program execution.
Variable Scope JavaScript has two variable scopes:
Global Variables: Declared outside any function, they have global scope and can be accessed anywhere in the code.
Local Variables: Declared within a function, they are visible only within that function. Function parameters are always local. A local variable with the same name as a global variable takes precedence within the function, effectively hiding the global variable.
Variable Names When naming variables, the following rules apply:
Reserved JavaScript keywords cannot be used.
They should not start with a numeral (0-9) but must begin with a letter or an underscore.
They are case-sensitive.
Reserved Words The tutorial provides a list of reserved words that cannot be used as identifiers in JavaScript.
Operators JavaScript supports various types of operators:
Arithmetic Operators: These include + (addition, also for string concatenation), – (subtraction), * (multiplication), / (division), % (modulus), ++ (increment), and — (decrement).
Comparison Operators: These include == (equal), != (not equal), > (greater than), < (less than), >= (greater than or equal to), and <= (less than or equal to).
Logical Operators: These include && (logical AND), || (logical OR), and ! (logical NOT).
Bitwise Operators: These operate on the bit level and include & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (bitwise NOT), << (left shift), >> (right shift), and >>> (right shift with zero).
Assignment Operators: These assign values to variables and include = (simple assignment), += (add and assignment), -= (subtract and assignment), *= (multiply and assignment), /= (divide and assignment), and %= (modulus and assignment). Similar assignment operators exist for bitwise operations (e.g., <<=, >>=, &=, |=, ^=).
Miscellaneous Operators:Conditional Operator (? 🙂: This is a ternary operator that evaluates a condition and returns one of two expressions based on the result.
typeof Operator: This unary operator returns a string indicating the data type of its operand (e.g., “number”, “string”, “boolean”, “object”, “function”, “undefined”). Note that typeof null returns “object”.
This covers the fundamental aspects of JavaScript as introduced in the “JavaScript Basics” part of the tutorial. The subsequent parts delve into JavaScript Objects and Advanced topics.
JavaScript Language Features: Core Concepts
Based on the “javascript_tutorial.pdf” and our previous discussion, let’s delve into the language features of JavaScript:
Core Characteristics:
JavaScript is a lightweight, interpreted programming language. It is also described as a dynamic computer programming language.
It is designed for creating network-centric applications and is most commonly used as a part of web pages. Its implementations allow client-side script to interact with the user and make dynamic pages.
JavaScript has object-oriented capabilities.
It is complementary to and integrated with Java and HTML. In fact, it is considered very easy to implement because it is integrated with HTML.
JavaScript is open and cross-platform.
The core of the language has been embedded in various web browsers like Netscape and Internet Explorer.
The ECMA-262 Specification defined a standard version of the core JavaScript language, and JavaScript 2.0 conforms to Edition 5 of this standard.
Data Types:
JavaScript allows you to work with three primitive data types: Numbers, Strings of text, and Boolean (true or false).
It also defines two trivial data types: null and undefined, each having a single value.
JavaScript supports a composite data type known as object.
Notably, JavaScript does not distinguish between integer values and floating-point values. All numbers are represented as 64-bit floating-point format defined by the IEEE 754 standard.
Variables:
JavaScript uses variables as named containers to store data.
Variables are declared using the var keyword. Multiple variables can be declared with a single var keyword.
Variable initialization involves storing a value in a variable, which can occur during declaration or later.
JavaScript is an untyped language, meaning a variable can hold a value of any data type, and this type can change during the program’s execution.
Variables have scope: global scope (defined outside functions, accessible anywhere) and local scope (defined within a function, visible only there). Local variables take precedence over global variables with the same name within a function.
There are rules for naming variables: they cannot be reserved keywords, should not start with a numeral, must begin with a letter or underscore, and are case-sensitive.
Operators: JavaScript supports a variety of operators to perform operations on operands:
Arithmetic Operators: +, -, *, /, %, ++, –. The addition operator + can also be used for string concatenation.
Miscellaneous Operators:Conditional Operator (? 🙂: A ternary operator for conditional expressions.
typeof Operator: A unary operator that returns a string indicating the data type of an operand.
Syntax:
JavaScript code is typically placed within <script>…</script> tags in an HTML document.
These <script> tags can be located in the <head> or <body> sections of the HTML. JavaScript can also be included from external .js files using the src attribute of the <script> tag.
Whitespace (spaces, tabs, newlines) is generally ignored, allowing for code formatting to enhance readability.
Semicolons at the end of simple statements are optional if each statement is on a new line, but using them is considered good practice.
JavaScript is case-sensitive.
Comments can be added using // for single-line comments and /* … */ for multi-line comments. It also recognizes <!– as a single-line HTML comment, and //–> is used to close JavaScript within HTML comments for compatibility with older browsers.
These features collectively define the fundamental characteristics and capabilities of the JavaScript language as outlined in the initial sections of the provided tutorial.
JavaScript Core Concepts
Based on the “javascript_tutorial.pdf” and our conversation history, here’s a discussion of the core concepts of JavaScript:
What JavaScript Is: At its core, JavaScript is a lightweight, interpreted programming language. It’s also described as a dynamic computer programming language. Its primary design purpose is for creating network-centric applications, and it is most commonly used as a part of web pages. This allows for client-side scripting, enabling web pages to interact with the user and become dynamic. JavaScript is considered complementary to and integrated with both Java and HTML. Its integration with HTML makes it very easy to implement. Furthermore, it’s an open and cross-platform language. The general-purpose core of JavaScript has been embedded in various web browsers.
Client-Side Focus:Client-side JavaScript is the most prevalent form of the language. For JavaScript code to be interpreted and executed by the browser, it needs to be included in or referenced by an HTML document. This client-side mechanism provides significant advantages, such as less server interaction (by validating user input before submission) and immediate feedback to visitors (without requiring a page reload). It also enables increased interactivity and richer interfaces on web pages.
Basic Syntax: JavaScript code is typically placed within <script>…</script> HTML tags. These tags alert the browser to interpret the enclosed text as a script. The <script> tag can have attributes like language (though this is being phased out) and type, with the recommended type being “text/javascript”.
Key aspects of JavaScript syntax include:
Whitespace and Line Breaks: JavaScript generally ignores spaces, tabs, and newlines, allowing for flexible code formatting to improve readability.
Semicolons: While semicolons are optional if each statement is on a new line, it is considered good programming practice to use them. They are mandatory when multiple statements are on a single line.
Case Sensitivity: JavaScript is case-sensitive, meaning that keywords, variables, function names, and other identifiers must have consistent capitalization (e.g., Time and TIME are different).
Comments: JavaScript supports both C-style (/* … */ for multi-line and // for single-line) and recognizes the HTML comment opening (<!– as a single-line comment) and closing (//–>) sequences.
Variables and Data Types: JavaScript uses variables as named containers to store data. Before using a variable, it must be declared using the var keyword. Multiple variables can be declared with a single var. Initialization is the process of assigning a value to a variable, which can happen at declaration or later.
JavaScript is an untyped language, meaning a single variable can hold values of different data types during its lifetime. It supports several primitive data types:
Numbers: All numbers are treated as floating-point values using the 64-bit IEEE 754 standard.
Strings: Represent sequences of text (e.g., “Hello”).
Boolean: Represents logical values (true or false).
Null: A trivial type with only one value: null.
Undefined: Another trivial type with only one value: undefined.
In addition to these, JavaScript has a composite data type called object. Variables have scope, which can be global (accessible anywhere) or local (accessible only within a function).
Operators: JavaScript provides various operators to perform operations on values (operands):
Comparison Operators: Compare two operands and return a boolean value (== equal, != not equal, > greater than, < less than, >= greater than or equal to, <= less than or equal to).
Bitwise Operators: Operate on the binary representation of integers (& AND, | OR, ^ XOR, ~ NOT, << left shift, >> right shift, >>> unsigned right shift).
Assignment Operators: Assign values to variables (= simple assignment, += add and assign, -= subtract and assign, *= multiply and assign, /= divide and assign, %= modulus and assign, and similar for bitwise operators).
Miscellaneous Operators: Include the conditional (ternary) operator (? 🙂 for concise conditional expressions and the typeof operator to determine the data type of a variable.
Placement in HTML: JavaScript code can be included in an HTML document in several ways:
Directly within the <head>…</head> section, often used for scripts that run on events or utility functions.
Directly within the <body>…</body> section, typically for scripts that generate content as the page loads.
In both the <head> and <body> sections.
In an external .js file, which is then linked into the HTML using the src attribute of the <script> tag in the <head>. This promotes code reusability across multiple HTML pages.
Understanding these core concepts provides a foundational understanding of how JavaScript functions and its role in web development as described in the sources.
JavaScript’s Web Integration: Core Concepts
Based on the “javascript_tutorial.pdf” and our conversation history, JavaScript’s integration with the web is a fundamental aspect of its design and usage. Here’s a discussion of this web integration:
Core Role in Web Pages: JavaScript is most commonly used as a part of web pages. Its implementations allow client-side scripts to interact with the user and make dynamic pages. This is a primary reason for JavaScript’s existence and widespread adoption.
Client-Side Scripting: JavaScript is fundamentally a client-side scripting language. This means that the JavaScript code is typically embedded in or referenced by an HTML document and is then interpreted and executed by the user’s web browser. This client-side execution enables interactivity and dynamic content generation directly within the browser.
Complementary to and Integrated with HTML: The tutorial emphasizes that JavaScript is complementary to and integrated with HTML. In fact, it is considered very easy to implement because it is integrated with HTML. This close relationship means that JavaScript code works within the structure and content defined by HTML.
Inclusion in HTML using <script> Tags: JavaScript code is embedded within HTML documents using the <script>…</script> tags. These tags serve as containers for JavaScript code and instruct the browser to interpret the content between them as a script. The <script> tag can take attributes such as language (typically “javascript”, though being phased out) and type (recommended to be “text/javascript”).
Placement of <script> Tags: The tutorial details various ways to place <script> tags within an HTML document:
<head>…</head> Section: Placing scripts in the <head> section is often done for scripts that need to run on specific events or for utility functions that might be used throughout the page.
<body>…</body> Section: If a script needs to run as the page loads and generate content directly into the page, it is typically placed in the <body> section.
Both <head> and <body> Sections: It is possible to include JavaScript in both sections of an HTML document.
External File: For larger projects and reusability, JavaScript code can be stored in external files with the .js extension and then included in HTML files using the src attribute of the <script> tag, usually placed in the <head>. This allows for maintaining identical code across multiple pages.
Dynamic Content and User Interaction: By being integrated into web pages, JavaScript enables them to be dynamic. It can interact with the user, respond to their actions (like button clicks or mouse hovers), control the browser, and dynamically create HTML content. For example, JavaScript can be used to validate form input before submitting it to the server.
Event Handling: JavaScript can “trap user-initiated events” such as button clicks and link navigation, allowing developers to execute specific code in response to these interactions. The tutorial later introduces the concept of “Events” and specific event types like onclick, onsubmit, and onmouseover/onmouseout, further illustrating this interaction.
Basic Output and DOM Manipulation (Implicit): While the Document Object Model (DOM) is formally introduced later in the tutorial, the early examples using document.write() demonstrate a basic level of interaction with the HTML document to output content. This is a fundamental aspect of JavaScript’s web integration – its ability to manipulate the structure and content of the web page.
Handling Browsers Without JavaScript: Recognizing that some browsers might not support JavaScript or have it disabled, the tutorial mentions the <noscript> tags. Content within these tags is displayed to users if their browser does not support JavaScript or if JavaScript is not enabled, allowing for a fallback mechanism or a warning message.
In summary, JavaScript’s web integration is characterized by its role as a client-side scripting language deeply intertwined with HTML, enabling dynamic behavior, user interaction, and content manipulation within web browsers. The <script> tag and its various placement options are key mechanisms for incorporating JavaScript into web pages, with external files promoting code organization and reusability.
JavaScript Development Tools: Simplicity and Enhanced Editors
Based on the “javascript_tutorial.pdf”, here’s a discussion of JavaScript development tools:
The tutorial points out that one of the significant advantages of JavaScript is that it does not require expensive development tools. You can begin writing JavaScript code with a simple text editor such as Notepad. Since JavaScript is an interpreted language within the context of a web browser, you don’t even need to buy a compiler.
However, the tutorial also mentions that various vendors have created nice JavaScript editing tools to make development simpler. Some of these tools listed in the source are:
Microsoft FrontPage: Described as a popular HTML editor that also provides web developers with JavaScript tools to assist in creating interactive websites.
Macromedia Dreamweaver MX: Identified as a very popular HTML and JavaScript editor among professional web developers. It offers prebuilt JavaScript components, integrates well with databases, and conforms to new standards like XHTML and XML.
Macromedia HomeSite 5: Presented as a well-liked HTML and JavaScript editor from Macromedia, suitable for effectively managing personal websites.
In summary, the tutorial highlights that basic JavaScript development can start with a simple text editor and a web browser. For more enhanced development experiences, dedicated HTML and JavaScript editors like Microsoft FrontPage, Macromedia Dreamweaver MX, and Macromedia HomeSite 5 are available, offering features that can simplify the process of building interactive websites. Our previous conversations have focused on the core concepts and web integration of JavaScript and did not delve into specific development tools beyond what is mentioned in this source.
Affiliate Disclosure: This blog may contain affiliate links, which means I may earn a small commission if you click on the link and make a purchase. This comes at no additional cost to you. I only recommend products or services that I believe will add value to my readers. Your support helps keep this blog running and allows me to continue providing you with quality content. Thank you for your support!
This tutorial serves as a guide for JavaScript beginners, aiming to impart foundational knowledge for creating dynamic web pages and applications. It begins with an introduction to JavaScript’s core concepts, including its syntax, how to enable it in browsers, and where to place code within HTML. The text then progresses to cover essential programming elements such as variables, data types, operators, control flow statements (like if-else and loops), and functions. Furthermore, the tutorial explores JavaScript objects, including built-in types like Number, String, and Array, as well as concepts like events and browser interactions. Finally, it touches upon more advanced topics such as error handling, form validation, and debugging, providing a comprehensive overview for newcomers to the language.
What are two key characteristics of JavaScript as a programming language, and for what primary purpose was it designed?
Explain the concept of client-side JavaScript and provide one advantage it offers over traditional server-side scripting.
Describe two limitations of client-side JavaScript that prevent it from being considered a full-fledged general-purpose programming language.
What are the standard HTML tags used to embed JavaScript code within a web page, and what are the recommended values for their key attributes?
Explain the significance of the var keyword in JavaScript and describe the difference between declaring and initializing a variable.
What are the two primary scopes of variables in JavaScript, and how does JavaScript handle variable names that exist in both scopes within a function?
Provide three examples of arithmetic operators in JavaScript and briefly explain their function.
Describe the purpose of comparison operators in JavaScript and give an example of a comparison that would evaluate to false if variable x holds the value 5 and variable y holds the value 10.
Explain the functionality of the logical AND (&&) operator in JavaScript. Under what condition will an expression using this operator evaluate to true?
What is the purpose of JavaScript events, and can you provide an example of a common HTML event and how it might be used with JavaScript?
Quiz Answer Key
JavaScript is a lightweight, interpreted programming language. It was primarily designed for creating network-centric applications and enhancing web pages with dynamic and interactive elements.
Client-side JavaScript is JavaScript code that is executed by the user’s web browser, rather than on a web server. One advantage is less server interaction, as user input can be validated in the browser before being sent to the server.
Two limitations of client-side JavaScript are its inability to read or write files (for security reasons) and its lack of built-in support for networking applications or multithreading/multiprocessing.
The standard HTML tags for embedding JavaScript are <script> and </script>. The recommended attribute to specify the scripting language is type with the value “text/javascript”. The language attribute is considered phased out in recent HTML versions.
The var keyword is used to declare variables in JavaScript, essentially creating a named container in memory. Declaration is simply stating the variable name (e.g., var myVariable;), while initialization is assigning an initial value to the variable (e.g., var myVariable = 10;).
The two primary scopes are global scope (variables defined anywhere in the code) and local scope (variables defined within a function). Within a function, a local variable with the same name as a global variable takes precedence, effectively hiding the global variable.
Examples of arithmetic operators include + (addition), – (subtraction), and * (multiplication). The addition operator adds two operands, the subtraction operator subtracts the second operand from the first, and the multiplication operator multiplies both operands.
Comparison operators in JavaScript are used to compare the values of two operands and return a Boolean value (true or false) based on the comparison. For example, (x > y) where x is 5 and y is 10 would evaluate to false.
The logical AND (&&) operator evaluates to true only if both of its operands (the expressions on either side of the operator) evaluate to true. If either operand is false, the entire expression will be false.
JavaScript events are actions or occurrences that happen in the browser, such as a user clicking a button or a page finishing loading. A common HTML event is onclick, which can be used to execute a JavaScript function when a user clicks on an HTML element.
Essay Format Questions
Discuss the advantages and limitations of using JavaScript for web development, considering its client-side nature and its integration with HTML. How has the evolution of web technologies addressed some of these limitations?
Explain the significance of variable scope in JavaScript, differentiating between global and local variables. Provide scenarios where understanding variable scope is crucial for avoiding errors and maintaining code functionality.
Compare and contrast the different types of operators available in JavaScript (arithmetic, comparison, logical, assignment). Provide examples of how each type of operator contributes to the functionality of a JavaScript program.
Describe the different ways JavaScript code can be placed within an HTML document, including the advantages and potential disadvantages of each method. When might you choose one placement method over another?
Discuss the fundamental data types supported by JavaScript. How does JavaScript’s handling of data types differ from strictly typed languages, and what are the implications of this dynamic typing?
Glossary of Key Terms
Interpreted Language: A programming language where the code is executed line by line by an interpreter, without the need for prior compilation into machine code.
Client-Side Scripting: Code that is executed by the user’s web browser, as opposed to being run on a web server.
Syntax: The set of rules that define the structure of a programming language, including how statements are written and organized.
Variable: A named storage location in a computer’s memory that can hold a value.
Declaration: The act of introducing a variable name to the program, indicating that a storage location will be used for that name.
Initialization: The act of assigning an initial value to a variable at the time of its creation or later in the program.
Scope: The region of a program where a particular variable can be accessed.
Global Variable: A variable that is declared outside of any function and can be accessed from any part of the JavaScript code.
Local Variable: A variable that is declared inside a function and can only be accessed within that function.
Operator: A symbol or keyword that performs an operation on one or more operands (values or variables).
Operand: A value or variable that an operator acts upon.
Arithmetic Operator: A symbol that performs mathematical calculations (e.g., addition, subtraction, multiplication).
Comparison Operator: A symbol that compares two operands and returns a Boolean value based on the relationship between them (e.g., equal to, greater than).
Logical Operator: A symbol that performs Boolean logic operations on one or more Boolean operands (e.g., AND, OR, NOT).
Assignment Operator: A symbol that assigns a value to a variable (e.g., =, +=).
Event: An action or occurrence that happens in the browser, such as a user interaction (e.g., clicking a button) or a browser process (e.g., page loading).
JavaScript Tutorial Briefing Document
Date: October 26, 2023 Source: Excerpts from “javascript_tutorial.pdf” (Tutorials Point, Copyright 2015)
Overview:
This document provides a briefing on the fundamental concepts of JavaScript as presented in the initial sections of the “javascript_tutorial.pdf”. The tutorial is designed for beginners with prior knowledge of HTML and some exposure to object-oriented programming and online application creation. It covers the basics of the language, including its nature, syntax, how to enable it in browsers, placement within HTML, fundamental data types, variables, operators, control flow statements (if-else, switch-case, loops), functions, events, cookies, page redirection, dialog boxes, the void keyword, and page printing. The document also introduces JavaScript objects and their basic properties and methods, including built-in objects like Number, Boolean, String, Array, Date, Math, and RegExp, as well as the Document Object Model (DOM). Finally, it touches upon advanced topics like errors and exceptions, form validation, animation, multimedia, debugging, image maps, and browser-specific information.
Part 1: JavaScript Basics
This section lays the groundwork for understanding JavaScript.
What is JavaScript? JavaScript is described as a “lightweight, interpreted programming language” primarily used for creating “network-centric applications” and adding interactivity to web pages. It is highlighted as “complimentary to and integrated with Java” and “HTML“, as well as being “open and cross-platform.” Its history is briefly mentioned, noting its initial name as LiveScript and its introduction in Netscape 2.0 in 1995. The importance of the ECMA-262 Specification for standardizing the core language is also noted.
Client-Side JavaScript: The tutorial emphasizes that client-side JavaScript, embedded in or referenced by HTML documents, is the most common form. It allows web pages to be dynamic, interact with users, control browsers, and dynamically create HTML content. Advantages over server-side scripts include “less server interaction“, “immediate feedback to the visitors“, “increased interactivity“, and “richer interfaces.” Limitations include the inability to read or write files (for security), lack of networking application support, and no multithreading or multiprocessor capabilities.
JavaScript Development Tools: The tutorial points out that JavaScript doesn’t require expensive tools, with a simple text editor being sufficient. Several more advanced editors like Microsoft FrontPage, Macromedia Dreamweaver MX, and Macromedia HomeSite 5 are also mentioned.
Where is JavaScript Today? The tutorial mentions ECMAScript Edition 5 as a significant update and notes that JavaScript 2.0 conforms to this standard with minor differences. It states that Netscape’s JavaScript and Microsoft’s JScript align with the ECMAScript standard while still supporting non-standard features.
JavaScript Syntax: JavaScript code is placed within <script>…</script> HTML tags. The <script> tag can be placed anywhere but is “normally recommended” within the <head> tags. Important attributes of the <script> tag are language (though phased out, typically “javascript”) and type (recommended, set to “text/javascript”). A basic “Hello World” example using document.write() is provided, along with the use of HTML comments (<!– … //–>) to handle browsers without JavaScript support, where // within the comment prevents the closing HTML comment tag from being interpreted as JavaScript. The tutorial clarifies that “JavaScript ignores spaces, tabs, and newlines” and that “Semicolons are Optional” if statements are on separate lines, although using them is good practice. Importantly, “JavaScript is a case-sensitive language.” Both // (single-line) and /* … */ (multi-line) comments are supported, and <!– is treated as a single-line JavaScript comment, with //–> being the recommended way to close an HTML comment containing JavaScript.
JavaScript Enabling: The tutorial provides step-by-step instructions on how to enable or disable JavaScript in various popular browsers: Internet Explorer, Firefox, Chrome, and Opera. The use of <noscript> tags to display a warning message to users with JavaScript disabled is also explained. For example:
<noscript>
Sorry…JavaScript is needed to go ahead.
</noscript>
JavaScript Placement: The tutorial details four ways to include JavaScript in HTML: within the <head>, within the <body>, in both <head> and <body>, and in an external .js file included using the src attribute of the <script> tag. Placing scripts in the <head> is suggested for scripts that run on events, while placing them in the <body> is for scripts that generate content on page load. External files (<script type=”text/javascript” src=”filename.js” ></script>) are recommended for reusing identical JavaScript code across multiple pages.
JavaScript Variables: JavaScript supports three primitive data types: “Numbers, e.g., 123, 120.50 etc.“, “Strings of text, e.g. ‘This text string’ etc.“, and “Boolean, e.g. true or false.“. It also defines trivial types null and undefined, and a composite type object. All numbers are treated as 64-bit floating-point values. Variables are declared using the var keyword (var money;, var money, name;). Initialization can occur at declaration or later (var name = “Ali”;, money = 2000.50;). Re-declaration of variables with the same name using var should be avoided. JavaScript is an “untyped language“, meaning a variable can hold any data type, and the type can change during execution. Variable scope is either global (defined anywhere) or local (visible only within a function). Local variables take precedence over global variables with the same name within a function. Rules for variable names include: no JavaScript reserved keywords, must not start with a numeral, must begin with a letter or underscore, and are case-sensitive. A comprehensive list of JavaScript reserved words is provided.
JavaScript Operators: An operator is defined as a symbol that performs an operation on operands (e.g., in 4 + 5 = 9, + is the operator, and 4 and 5 are operands). The tutorial covers arithmetic operators (+, -, *, /, %, ++, –, noting that + can also concatenate strings), comparison operators (==, !=, >, <, >=, <=), logical operators (&&, ||, !), bitwise operators (&, |, ^, ~, <<, >>, >>>), assignment operators (=, +=, -=, *=, /=, %=, and their bitwise counterparts), and miscellaneous operators, specifically the conditional (ternary) operator (? 🙂 and the typeof operator. The typeof operator returns a string indicating the data type of its operand (e.g., “number”, “string”, “boolean”, “object”, “function”, “undefined”). Examples are provided for each operator type. For instance, regarding the conditional operator:
result = (a > b) ? 100 : 200;
This assigns 100 to result if a is greater than b, and 200 otherwise.
Part 2: JavaScript Objects
This section introduces the concept of objects in JavaScript.
JavaScript Objects: An object is a collection of properties (named values) and methods (functions that can be performed on the object). The tutorial covers user-defined objects, defining methods for objects, and the use of the with keyword (though often discouraged).
Built-in Objects: The tutorial then delves into various built-in JavaScript objects, detailing their properties and methods with examples:
Number: Properties like MAX_VALUE, MIN_VALUE, NaN, NEGATIVE_INFINITY, POSITIVE_INFINITY, prototype, constructor, and methods like toExponential(), toFixed(), toLocaleString(), toPrecision(), toString(), valueOf().
Boolean: Properties constructor, prototype, and methods toSource(), toString(), valueOf().
String: Properties constructor, length, prototype, and numerous methods for string manipulation (e.g., charAt(), charCodeAt(), concat(), indexOf(), lastIndexOf(), slice(), split(), replace(), search(), toLowerCase(), toUpperCase(), etc.) and HTML wrappers (e.g., anchor(), bold(), italics(), link()).
Date: Properties constructor, prototype, various methods for getting and setting date and time components (e.g., getDate(), getDay(), getFullYear(), getHours(), setDate(), setFullYear(), setHours(), getTime(), setTime(), and their UTC counterparts), as well as methods for converting dates to string formats (e.g., toDateString(), toGMTString(), toLocaleDateString(), toString(), toTimeString(), toUTCString(), valueOf()). Static methods Date.parse() and Date.UTC() are also covered.
Math: Properties for mathematical constants (e.g., Math.E, Math.PI, Math.LN2, Math.LOG2E, Math.SQRT2) and a wide range of mathematical functions as methods (e.g., abs(), acos(), asin(), atan(), ceil(), cos(), exp(), floor(), log(), max(), min(), pow(), random(), round(), sin(), sqrt(), tan()).
RegExp: Covers regular expressions, including brackets, quantifiers, literal characters, metacharacters, and modifiers. Properties like constructor, global, ignoreCase, lastIndex, multiline, source, and methods exec(), test(), toSource(), toString().
DOM (Document Object Model): Briefly introduces the DOM, mentioning “The Legacy DOM”, “The W3C DOM”, and “The IE 4 DOM”, as well as “DOM Compatibility”.
Part 3: JavaScript Advanced
This section touches upon more advanced JavaScript concepts.
Errors and Exceptions: Discusses syntax errors, runtime errors, and logical errors. It introduces the try…catch…finally statement for error handling, the throw statement for raising custom exceptions, and the onerror() method.
Form Validation: Covers basic and data format validation techniques in JavaScript to ensure user input is correct before submission.
Animation: Introduces manual and automated animation techniques using JavaScript, including rollover effects with mouse events.
Multimedia: Briefly mentions checking for browser plug-ins and controlling multimedia elements using JavaScript.
Debugging: Provides information on error messages in different browsers (IE, Firefox/Mozilla), error notifications, and general tips for debugging JavaScript code.
Image Map: Covers the implementation of image maps using JavaScript.
Browsers: Discusses the navigator object and its properties (e.g., appName, appVersion, userAgent) and methods, as well as techniques for browser detection.
Key Themes and Important Ideas:
JavaScript as a Client-Side Scripting Language: The primary role of JavaScript is to enhance HTML and create dynamic and interactive web pages by running in the user’s browser.
Ease of Implementation: JavaScript is presented as easy to start with, requiring just a text editor and a web browser.
Integration with HTML: JavaScript code is embedded within HTML using <script> tags, allowing for close interaction between the structure and behavior of a web page.
Fundamental Programming Concepts: The tutorial covers core programming concepts like variables, data types, operators, control flow statements (conditionals and loops), and functions, providing a foundation for writing more complex scripts.
Object-Oriented Capabilities: While described as interpreted, JavaScript is also highlighted as having object-oriented capabilities, with the introduction of objects, properties, and methods.
Built-in Functionality: JavaScript provides a rich set of built-in objects (Number, Boolean, String, Array, Date, Math, RegExp) with numerous properties and methods that simplify common programming tasks.
Event Handling: JavaScript enables the creation of interactive web pages by allowing scripts to respond to user-initiated events (e.g., onclick, onsubmit, onmouseover).
Browser Interaction: JavaScript can interact with the browser environment, including handling cookies, performing page redirects and refreshes, and displaying dialog boxes.
Error Handling and Validation: The tutorial introduces mechanisms for handling errors and validating user input, crucial for creating robust web applications.
Quotes:
“JavaScript is a lightweight, interpreted programming language.” (About the Tutorial, p. i)
“Designed for creating network-centric applications.” (About the Tutorial, p. i)
“It is complimentary to and integrated with Java.” (About the Tutorial, p. i)
“It is complimentary to and integrated with HTML.” (About the Tutorial, p. i)
“Client-side JavaScript is the most common form of the language. The script should be included in or referenced by an HTML document for the code to be interpreted by the browser.” (JAVASCRIPT – Overview, p. 11)
“You can place the
Understanding JavaScript Fundamentals and Web Browser Integration
What is JavaScript and what are its key characteristics?
JavaScript is a lightweight, interpreted programming language primarily designed for creating network-centric applications. It’s known for being easy to implement due to its integration with HTML, and it’s an open and cross-platform language. It allows for client-side scripting to create dynamic and interactive web pages.
Who is the intended audience for this tutorial and what prior knowledge is expected?
This tutorial is designed for JavaScript beginners who want to understand the fundamental functionalities of JavaScript to build dynamic web pages and web applications. It assumes that the reader has prior knowledge of HTML coding and some exposure to object-oriented programming concepts and creating online applications.
What are some of the advantages of using client-side JavaScript in web development?
Client-side JavaScript offers several benefits, including reduced server interaction by enabling input validation before submission, immediate feedback to users without page reloads, increased interactivity through features like mouse hover effects, and richer user interfaces with elements like drag-and-drop components.
What are some limitations of JavaScript that prevent it from being considered a full-fledged programming language?
Despite its capabilities, client-side JavaScript has limitations. For security reasons, it cannot read or write files. It also lacks built-in support for networking applications and does not have multithreading or multiprocessor capabilities.
How is JavaScript typically included and placed within an HTML document?
JavaScript code is included within HTML documents using the <script> tags. These tags can be placed in the <head>, the <body>, or both sections of the HTML. Additionally, JavaScript code can be stored in an external .js file and linked to the HTML document using the src attribute of the <script> tag. It is often recommended to place script tags in the <head> for scripts that run on events or in the <body> for scripts that generate content on page load.
What are variables in JavaScript and what are the rules for naming them?
In JavaScript, variables are named containers used to store data. Before using a variable, it must be declared using the var keyword (though modern JavaScript introduces let and const). Variable names must not be JavaScript reserved keywords, should not start with a numeral, must begin with a letter or an underscore, and are case-sensitive.
What are the different types of operators available in JavaScript and what are their basic functionalities?
JavaScript supports various types of operators, including:
Bitwise Operators: Perform operations on the binary representations of numbers (e.g., &, |, ^, ~, <<, >>, >>>).
Miscellaneous Operators: Include the conditional (ternary) operator ?: and the typeof operator to determine the data type of a variable.
How can users enable or disable JavaScript support in common web browsers like Internet Explorer, Firefox, and Chrome?
The tutorial provides step-by-step instructions for enabling and disabling JavaScript in Internet Explorer (via Internet Options > Security > Custom Level > Scripting > Active scripting), Firefox (by toggling the javascript.enabled setting in about:config), Chrome (via Settings > Show advanced settings > Content settings > Javascript), and Opera (via Tools > Preferences > Advanced > Content > Enable JavaScript). It also mentions using the <noscript> tag to display a warning to users with JavaScript disabled.
JavaScript Basics: A Beginner’s Guide
Let’s discuss JavaScript Basics based on the provided tutorial.
What is JavaScript? JavaScript is described as a lightweight, interpreted programming language. It is designed for creating network-centric applications and is commonly used as part of web pages to enable client-side scripts that can interact with the user and create dynamic pages. JavaScript has object-oriented capabilities and is complementary to and integrated with Java and HTML. It is also considered open and cross-platform and very easy to implement because it is integrated with HTML. It was initially known as LiveScript but was renamed JavaScript by Netscape, possibly due to the popularity of Java. JavaScript first appeared in Netscape 2.0 in 1995.
Audience and Prerequisites The tutorial is prepared for JavaScript beginners to help them understand the basic functionality for building dynamic web pages and web applications. It is assumed that the reader has prior knowledge of HTML coding. Some prior exposure to object-oriented programming concepts and a general idea of creating online applications would also be helpful.
Client-Side JavaScriptClient-side JavaScript is the most common form of the language. For the code to be interpreted by the browser, the script needs to be included in or referenced by an HTML document. This allows web pages to be dynamic, interacting with users, controlling the browser, and dynamically creating HTML content. Client-side JavaScript offers advantages over traditional server-side scripts, such as less server interaction, immediate feedback to visitors, increased interactivity, and richer interfaces.
Limitations of JavaScript Despite its capabilities, JavaScript is not considered a full-fledged programming language and has limitations. Client-side JavaScript does not allow reading or writing files for security reasons. It also lacks support for networking applications, multithreading, and multiprocessor capabilities. However, it excels at adding interactivity to static HTML pages.
JavaScript Development Tools A major advantage of JavaScript is that it does not require expensive development tools. You can start with a simple text editor like Notepad. As it’s an interpreted language within a web browser, a compiler is not needed. Several vendors offer more advanced JavaScript editing tools, such as Microsoft FrontPage, Macromedia Dreamweaver MX, and Macromedia HomeSite 5.
Where is JavaScript Today? Modern JavaScript implementations like Netscape’s JavaScript and Microsoft’s JScript conform to the ECMAScript standard.
Including JavaScript in HTML (Placement) JavaScript code is implemented using <script>…</script> HTML tags in a web page. These tags can be placed anywhere within the web page, but it is generally recommended to keep them within the <head> tags. The <script> tag signals the browser to interpret the text within it as a script. The <script> tag can have attributes like language (though its use is being phased out) and type, which should be set to “text/javascript”.
There are preferred ways to include JavaScript in an HTML file:
In the <head>…</head> section: This is often used for scripts that run on events, like user clicks.
In the <body>…</body> section: Scripts placed here typically run as the page loads to generate content.
In both <head> and <body> sections: You can have scripts in both sections.
In an external file: For reusing code across multiple pages, JavaScript can be stored in a .js file and included using the src attribute of the <script> tag in the <head> section.
Basic Syntax
Whitespace and Line Breaks: JavaScript ignores spaces, tabs, and newlines, allowing for flexible formatting to improve readability.
Semicolons: Semicolons at the end of simple statements are generally optional if each statement is on a separate line. However, it’s good programming practice to use semicolons.
Case Sensitivity: JavaScript is case-sensitive. Keywords, variables, function names, and identifiers must have consistent capitalization (e.g., Time and TIME are different).
Comments: JavaScript supports C-style (/* … */ for multi-line and single-line) and C++-style (// for single-line) comments. It also recognizes the HTML comment opening <!– as a single-line comment but requires the closing –> to be written as //–> to avoid being read as JavaScript code.
Enabling JavaScript in Browsers The tutorial outlines how to enable JavaScript in various browsers:
Internet Explorer: Through Tools -> Internet Options -> Security Tab -> Custom Level -> Scripting -> Active Scripting -> Enable.
Firefox: By typing about:config in the address bar, accepting the warning, searching for javascript.enabled, and toggling its value.
Chrome: Via Chrome menu -> Settings -> Show advanced settings -> Privacy -> Content settings -> Javascript and selecting the desired option.
Warning for Non-JavaScript Browsers The <noscript> tags can be used to display a warning message to users whose browsers do not support JavaScript or have it disabled. The content within <noscript> tags is displayed in place of the JavaScript code in such cases.
Variables JavaScript allows working with three primitive data types: Numbers, Strings, and Boolean. It also defines two trivial data types: null and undefined. Additionally, JavaScript supports a composite data type: object. Importantly, JavaScript does not distinguish between integer and floating-point numbers; all numbers are represented as 64-bit floating-point values according to the IEEE 754 standard.
Variables are named containers for storing data. They are declared using the var keyword. Multiple variables can be declared with a single var keyword. Variable initialization is the process of storing a value in a variable, which can happen at the time of declaration or later. The var keyword should only be used for the initial declaration or initialization of a variable. JavaScript is an untyped language, meaning a variable can hold a value of any data type, and the type can change during program execution.
Variable Scope JavaScript has two variable scopes:
Global Variables: Declared outside any function, they have global scope and can be accessed anywhere in the code.
Local Variables: Declared within a function, they are visible only within that function. Function parameters are always local. A local variable with the same name as a global variable takes precedence within the function, effectively hiding the global variable.
Variable Names When naming variables, the following rules apply:
Reserved JavaScript keywords cannot be used.
They should not start with a numeral (0-9) but must begin with a letter or an underscore.
They are case-sensitive.
Reserved Words The tutorial provides a list of reserved words that cannot be used as identifiers in JavaScript.
Operators JavaScript supports various types of operators:
Arithmetic Operators: These include + (addition, also for string concatenation), – (subtraction), * (multiplication), / (division), % (modulus), ++ (increment), and — (decrement).
Comparison Operators: These include == (equal), != (not equal), > (greater than), < (less than), >= (greater than or equal to), and <= (less than or equal to).
Logical Operators: These include && (logical AND), || (logical OR), and ! (logical NOT).
Bitwise Operators: These operate on the bit level and include & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (bitwise NOT), << (left shift), >> (right shift), and >>> (right shift with zero).
Assignment Operators: These assign values to variables and include = (simple assignment), += (add and assignment), -= (subtract and assignment), *= (multiply and assignment), /= (divide and assignment), and %= (modulus and assignment). Similar assignment operators exist for bitwise operations (e.g., <<=, >>=, &=, |=, ^=).
Miscellaneous Operators:Conditional Operator (? 🙂: This is a ternary operator that evaluates a condition and returns one of two expressions based on the result.
typeof Operator: This unary operator returns a string indicating the data type of its operand (e.g., “number”, “string”, “boolean”, “object”, “function”, “undefined”). Note that typeof null returns “object”.
This covers the fundamental aspects of JavaScript as introduced in the “JavaScript Basics” part of the tutorial. The subsequent parts delve into JavaScript Objects and Advanced topics.
JavaScript Language Features: Core Concepts
Based on the “javascript_tutorial.pdf” and our previous discussion, let’s delve into the language features of JavaScript:
Core Characteristics:
JavaScript is a lightweight, interpreted programming language. It is also described as a dynamic computer programming language.
It is designed for creating network-centric applications and is most commonly used as a part of web pages. Its implementations allow client-side script to interact with the user and make dynamic pages.
JavaScript has object-oriented capabilities.
It is complementary to and integrated with Java and HTML. In fact, it is considered very easy to implement because it is integrated with HTML.
JavaScript is open and cross-platform.
The core of the language has been embedded in various web browsers like Netscape and Internet Explorer.
The ECMA-262 Specification defined a standard version of the core JavaScript language, and JavaScript 2.0 conforms to Edition 5 of this standard.
Data Types:
JavaScript allows you to work with three primitive data types: Numbers, Strings of text, and Boolean (true or false).
It also defines two trivial data types: null and undefined, each having a single value.
JavaScript supports a composite data type known as object.
Notably, JavaScript does not distinguish between integer values and floating-point values. All numbers are represented as 64-bit floating-point format defined by the IEEE 754 standard.
Variables:
JavaScript uses variables as named containers to store data.
Variables are declared using the var keyword. Multiple variables can be declared with a single var keyword.
Variable initialization involves storing a value in a variable, which can occur during declaration or later.
JavaScript is an untyped language, meaning a variable can hold a value of any data type, and this type can change during the program’s execution.
Variables have scope: global scope (defined outside functions, accessible anywhere) and local scope (defined within a function, visible only there). Local variables take precedence over global variables with the same name within a function.
There are rules for naming variables: they cannot be reserved keywords, should not start with a numeral, must begin with a letter or underscore, and are case-sensitive.
Operators: JavaScript supports a variety of operators to perform operations on operands:
Arithmetic Operators: +, -, *, /, %, ++, –. The addition operator + can also be used for string concatenation.
Miscellaneous Operators:Conditional Operator (? 🙂: A ternary operator for conditional expressions.
typeof Operator: A unary operator that returns a string indicating the data type of an operand.
Syntax:
JavaScript code is typically placed within <script>…</script> tags in an HTML document.
These <script> tags can be located in the <head> or <body> sections of the HTML. JavaScript can also be included from external .js files using the src attribute of the <script> tag.
Whitespace (spaces, tabs, newlines) is generally ignored, allowing for code formatting to enhance readability.
Semicolons at the end of simple statements are optional if each statement is on a new line, but using them is considered good practice.
JavaScript is case-sensitive.
Comments can be added using // for single-line comments and /* … */ for multi-line comments. It also recognizes <!– as a single-line HTML comment, and //–> is used to close JavaScript within HTML comments for compatibility with older browsers.
These features collectively define the fundamental characteristics and capabilities of the JavaScript language as outlined in the initial sections of the provided tutorial.
JavaScript Core Concepts
Based on the “javascript_tutorial.pdf” and our conversation history, here’s a discussion of the core concepts of JavaScript:
What JavaScript Is: At its core, JavaScript is a lightweight, interpreted programming language. It’s also described as a dynamic computer programming language. Its primary design purpose is for creating network-centric applications, and it is most commonly used as a part of web pages. This allows for client-side scripting, enabling web pages to interact with the user and become dynamic. JavaScript is considered complementary to and integrated with both Java and HTML. Its integration with HTML makes it very easy to implement. Furthermore, it’s an open and cross-platform language. The general-purpose core of JavaScript has been embedded in various web browsers.
Client-Side Focus:Client-side JavaScript is the most prevalent form of the language. For JavaScript code to be interpreted and executed by the browser, it needs to be included in or referenced by an HTML document. This client-side mechanism provides significant advantages, such as less server interaction (by validating user input before submission) and immediate feedback to visitors (without requiring a page reload). It also enables increased interactivity and richer interfaces on web pages.
Basic Syntax: JavaScript code is typically placed within <script>…</script> HTML tags. These tags alert the browser to interpret the enclosed text as a script. The <script> tag can have attributes like language (though this is being phased out) and type, with the recommended type being “text/javascript”.
Key aspects of JavaScript syntax include:
Whitespace and Line Breaks: JavaScript generally ignores spaces, tabs, and newlines, allowing for flexible code formatting to improve readability.
Semicolons: While semicolons are optional if each statement is on a new line, it is considered good programming practice to use them. They are mandatory when multiple statements are on a single line.
Case Sensitivity: JavaScript is case-sensitive, meaning that keywords, variables, function names, and other identifiers must have consistent capitalization (e.g., Time and TIME are different).
Comments: JavaScript supports both C-style (/* … */ for multi-line and // for single-line) and recognizes the HTML comment opening (<!– as a single-line comment) and closing (//–>) sequences.
Variables and Data Types: JavaScript uses variables as named containers to store data. Before using a variable, it must be declared using the var keyword. Multiple variables can be declared with a single var. Initialization is the process of assigning a value to a variable, which can happen at declaration or later.
JavaScript is an untyped language, meaning a single variable can hold values of different data types during its lifetime. It supports several primitive data types:
Numbers: All numbers are treated as floating-point values using the 64-bit IEEE 754 standard.
Strings: Represent sequences of text (e.g., “Hello”).
Boolean: Represents logical values (true or false).
Null: A trivial type with only one value: null.
Undefined: Another trivial type with only one value: undefined.
In addition to these, JavaScript has a composite data type called object. Variables have scope, which can be global (accessible anywhere) or local (accessible only within a function).
Operators: JavaScript provides various operators to perform operations on values (operands):
Comparison Operators: Compare two operands and return a boolean value (== equal, != not equal, > greater than, < less than, >= greater than or equal to, <= less than or equal to).
Bitwise Operators: Operate on the binary representation of integers (& AND, | OR, ^ XOR, ~ NOT, << left shift, >> right shift, >>> unsigned right shift).
Assignment Operators: Assign values to variables (= simple assignment, += add and assign, -= subtract and assign, *= multiply and assign, /= divide and assign, %= modulus and assign, and similar for bitwise operators).
Miscellaneous Operators: Include the conditional (ternary) operator (? 🙂 for concise conditional expressions and the typeof operator to determine the data type of a variable.
Placement in HTML: JavaScript code can be included in an HTML document in several ways:
Directly within the <head>…</head> section, often used for scripts that run on events or utility functions.
Directly within the <body>…</body> section, typically for scripts that generate content as the page loads.
In both the <head> and <body> sections.
In an external .js file, which is then linked into the HTML using the src attribute of the <script> tag in the <head>. This promotes code reusability across multiple HTML pages.
Understanding these core concepts provides a foundational understanding of how JavaScript functions and its role in web development as described in the sources.
JavaScript’s Web Integration: Core Concepts
Based on the “javascript_tutorial.pdf” and our conversation history, JavaScript’s integration with the web is a fundamental aspect of its design and usage. Here’s a discussion of this web integration:
Core Role in Web Pages: JavaScript is most commonly used as a part of web pages. Its implementations allow client-side scripts to interact with the user and make dynamic pages. This is a primary reason for JavaScript’s existence and widespread adoption.
Client-Side Scripting: JavaScript is fundamentally a client-side scripting language. This means that the JavaScript code is typically embedded in or referenced by an HTML document and is then interpreted and executed by the user’s web browser. This client-side execution enables interactivity and dynamic content generation directly within the browser.
Complementary to and Integrated with HTML: The tutorial emphasizes that JavaScript is complementary to and integrated with HTML. In fact, it is considered very easy to implement because it is integrated with HTML. This close relationship means that JavaScript code works within the structure and content defined by HTML.
Inclusion in HTML using <script> Tags: JavaScript code is embedded within HTML documents using the <script>…</script> tags. These tags serve as containers for JavaScript code and instruct the browser to interpret the content between them as a script. The <script> tag can take attributes such as language (typically “javascript”, though being phased out) and type (recommended to be “text/javascript”).
Placement of <script> Tags: The tutorial details various ways to place <script> tags within an HTML document:
<head>…</head> Section: Placing scripts in the <head> section is often done for scripts that need to run on specific events or for utility functions that might be used throughout the page.
<body>…</body> Section: If a script needs to run as the page loads and generate content directly into the page, it is typically placed in the <body> section.
Both <head> and <body> Sections: It is possible to include JavaScript in both sections of an HTML document.
External File: For larger projects and reusability, JavaScript code can be stored in external files with the .js extension and then included in HTML files using the src attribute of the <script> tag, usually placed in the <head>. This allows for maintaining identical code across multiple pages.
Dynamic Content and User Interaction: By being integrated into web pages, JavaScript enables them to be dynamic. It can interact with the user, respond to their actions (like button clicks or mouse hovers), control the browser, and dynamically create HTML content. For example, JavaScript can be used to validate form input before submitting it to the server.
Event Handling: JavaScript can “trap user-initiated events” such as button clicks and link navigation, allowing developers to execute specific code in response to these interactions. The tutorial later introduces the concept of “Events” and specific event types like onclick, onsubmit, and onmouseover/onmouseout, further illustrating this interaction.
Basic Output and DOM Manipulation (Implicit): While the Document Object Model (DOM) is formally introduced later in the tutorial, the early examples using document.write() demonstrate a basic level of interaction with the HTML document to output content. This is a fundamental aspect of JavaScript’s web integration – its ability to manipulate the structure and content of the web page.
Handling Browsers Without JavaScript: Recognizing that some browsers might not support JavaScript or have it disabled, the tutorial mentions the <noscript> tags. Content within these tags is displayed to users if their browser does not support JavaScript or if JavaScript is not enabled, allowing for a fallback mechanism or a warning message.
In summary, JavaScript’s web integration is characterized by its role as a client-side scripting language deeply intertwined with HTML, enabling dynamic behavior, user interaction, and content manipulation within web browsers. The <script> tag and its various placement options are key mechanisms for incorporating JavaScript into web pages, with external files promoting code organization and reusability.
JavaScript Development Tools: Simplicity and Enhanced Editors
Based on the “javascript_tutorial.pdf”, here’s a discussion of JavaScript development tools:
The tutorial points out that one of the significant advantages of JavaScript is that it does not require expensive development tools. You can begin writing JavaScript code with a simple text editor such as Notepad. Since JavaScript is an interpreted language within the context of a web browser, you don’t even need to buy a compiler.
However, the tutorial also mentions that various vendors have created nice JavaScript editing tools to make development simpler. Some of these tools listed in the source are:
Microsoft FrontPage: Described as a popular HTML editor that also provides web developers with JavaScript tools to assist in creating interactive websites.
Macromedia Dreamweaver MX: Identified as a very popular HTML and JavaScript editor among professional web developers. It offers prebuilt JavaScript components, integrates well with databases, and conforms to new standards like XHTML and XML.
Macromedia HomeSite 5: Presented as a well-liked HTML and JavaScript editor from Macromedia, suitable for effectively managing personal websites.
In summary, the tutorial highlights that basic JavaScript development can start with a simple text editor and a web browser. For more enhanced development experiences, dedicated HTML and JavaScript editors like Microsoft FrontPage, Macromedia Dreamweaver MX, and Macromedia HomeSite 5 are available, offering features that can simplify the process of building interactive websites. Our previous conversations have focused on the core concepts and web integration of JavaScript and did not delve into specific development tools beyond what is mentioned in this source.
Affiliate Disclosure: This blog may contain affiliate links, which means I may earn a small commission if you click on the link and make a purchase. This comes at no additional cost to you. I only recommend products or services that I believe will add value to my readers. Your support helps keep this blog running and allows me to continue providing you with quality content. Thank you for your support!
This document offers an introduction to JavaScript programming, starting with fundamental concepts like saving files, executing code in environments like Node.js, and understanding the difference between the language and its runtime environment. It progresses to explain JavaScript syntax, comparing it to English, and introduces variables, their declaration keywords (let, var, const), and naming conventions. The text then explores data types (number, string, boolean, undefined), type coercion, and essential operators for various operations. Further topics include arrays for managing lists of data, functions (declarations, expressions, immediately invoked function expressions), decision statements (if, switch, ternary), and iteration (for, while loops). It also covers variable scope, the module pattern for managing global scope issues, closures, the behavior of the ‘this’ keyword, destructuring arrays and objects, and template literals for flexible string creation. Finally, it touches upon regular expressions, built-in native objects like String and Array, constructor functions, the conceptual equivalence of classes in JavaScript, and arrow functions, concluding with a brief overview of the Date object and useful string and array methods.
JavaScript Foundations From Variables to Functions by Bob Tabor amjadizhar blog
JavaScript Fundamentals: A Beginner’s Guide
JavaScript is a popular programming language, and this course is designed for absolute beginners, including those new to programming in general. It assumes some familiarity with HTML and CSS and focuses on teaching the pure JavaScript language rather than being a web development course, although JavaScript’s use in web browsers will be discussed towards the end. The course emphasizes writing console or command-line style applications to isolate the language itself from HTML and CSS complexities.
Here are some fundamental aspects of JavaScript:
Tools for Development
You will need a web browser (Microsoft Edge or Google Chrome are recommended).
Node.js is required as the JavaScript runtime environment to execute code. It’s essentially the V8 JavaScript engine from Chrome with added tools for server-side functionalities, though for this course, it’s used for simple console output.
An authoring tool like Visual Studio Code (VS Code) is highly recommended. It’s free, cross-platform, and provides features like code coloring, code completion (IntelliSense), file management, and an integrated terminal.
Execution Environments JavaScript code can be executed in several environments:
Node.js: Typically used for server-side applications that interact with the file system, network, or handle HTTP requests/responses.
Web Browser: Used for dynamically interacting with HTML elements on a web page.
Other environments: Like Unity for video game development. It’s important to understand the distinction between the JavaScript language itself and the environment it runs in. For instance, console.log exists in both Node.js (to print to the command line) and web browsers (for debugging messages in developer tools).
Language Fundamentals
Statements and Expressions:
A statement is a complete instruction, like a sentence in English, ending with a semicolon. JavaScript files contain one or more statements executed sequentially.
A statement consists of one or more expressions.
An expression is made up of operators (like keywords, +, =) and operands (like variable names or function calls).
Examples of expressions include variable declarations (let a), value assignments (a = 4), and evaluations that return a single value (b + c).
Case Sensitivity: JavaScript is case-sensitive. console with a capital ‘C’ is different from console with a lowercase ‘c’.
Comments:
Single-line comments start with two forward slashes (//).
Multi-line comments start with /* and end with */.
Variables
A variable is an area in the computer’s memory to store and retrieve values.
Declaration Keywords:
let: The recommended keyword for declaring variables in modern JavaScript, behaving like variables in most other programming languages.
var: The original keyword, still widely seen in tutorials and articles, but its usage is nuanced and can lead to unexpected ramifications due to its scope behavior.
const: Used for variables whose values are not intended to change after initialization. Attempting to reassign a const variable will result in an error.
Naming Rules for Identifiers:
Must begin with a letter, dollar sign ($), or an underscore (_).
Can contain letters, numbers, dollar signs, or underscores.
Cannot contain spaces or other special characters.
Cannot be a keyword (e.g., let cannot be a variable name).
Are case-sensitive (x is different from X).
Naming Conventions (Best Practices):
Descriptive names: Should represent the data being stored (e.g., firstNumber instead of x).
Camel casing: First word lowercase, subsequent words capitalized (e.g., firstName, zipCode).
Consistency: Maintain a consistent naming style throughout the application.
Avoid relying on case: Don’t create variables like zipCode and ZipCode as separate entities, as it reduces readability.
Assignment Operator (=): Used to assign a value to a variable. A variable can be declared once but assigned values multiple times.
Initialization: Assigning a value to a variable at the moment of declaration (e.g., let x = 7). If not initialized, a variable’s value is undefined.
Scope (Basic): Variables have a lifespan and citizenship determined by where they are declared.
Variables declared in an outer scope are visible in all inner (child) scopes.
Variables declared in an inner scope are not available in outer scopes; they “die” and are removed from memory once their code block finishes execution.
Data Types
In JavaScript, values have data types, not the variables themselves. A variable can hold different types of values over its lifespan.
Primitive Data Types:
Number: Any positive or negative number, including decimals.
Boolean: true or false.
String: A sequence of characters, usually represented with single or double quotes (e.g., ‘hello world’).
Undefined: The value a variable has when declared but not yet assigned a value.
Null: Represents a variable that points to nothing, typically when an object reference was expected. It’s considered an object type when using typeof due to a known bug.
Symbol: A new primitive type in the latest JavaScript version, not covered in depth.
Complex Data Types:
Object: A collection of related properties and methods. Arrays are a type of object.
Function: A block of code that can be named and called. Functions are also considered a data type.
Type Coercion
JavaScript can automatically coerce (convert) data types when incompatible types are used together (e.g., adding a number and a string will convert the number to a string and then concatenate them).
Explicit Coercion: You can force conversion using built-in functions like parseInt() to convert a string to an integer, specifying the radix (base system, usually 10).
NaN (Not a Number): Returned by parseInt() or other numeric operations if the conversion or calculation results in something that isn’t a valid number. isNaN() can be used to check for this.
Increment/Decrement: ++ (increments by 1), — (decrements by 1). Can be prefix (++a, first evaluate then use) or postfix (a++, first use then evaluate).
Modulus (%): Returns the remainder of a division.
String Operators: Single/double quotes for literal strings, + for string concatenation.
Precedence: Parentheses () control the order of operations, similar to algebra.
Function Invocation: () after a function name to execute it.
Member Accessor: . (dot notation) to access properties or methods of an object (e.g., console.log).
Array Element Access: Square brackets [] to access elements in an array by index (e.g., a).
Logical Operators: && (AND), || (OR) for combining conditions.
Equality Operators:
== (equality): Checks if two values are equal, performing type coercion if necessary.
=== (strict equality): Checks if two values are equal AND of the same data type, without coercion.
!= (not equal to): Checks for inequality.
!== (strict not equal to): Checks for strict inequality.
Functions
A function is a named block of reusable code.
Function Declaration: Defined using the function keyword, an identifier (name), parameters in parentheses, and a body in curly braces (e.g., function sayHello() { … }).
Function Expression: A function defined as part of an expression, often assigned to a variable, and can be anonymous (without a name). Useful for callbacks.
Arguments/Parameters: Values passed into a function, defined within the parentheses.
Return Values: Functions can return a single value using the return keyword.
Immediately Invoked Function Expression (IIFE): A function expression that is defined and executed immediately. It’s enclosed in parentheses and followed by another set of parentheses for invocation (e.g., (function() { … })();). Often used to create a private scope.
Arrow Functions: A concise, shorthand syntax for writing function expressions, especially useful for simple functions or callbacks. They use => (fat arrow operator).
Decision Statements
if-else if-else: Executes different blocks of code based on conditions that evaluate to true or false.
switch: Evaluates an expression against multiple case values. Uses break statements to exit a case block and prevent “fall-through”.
Ternary Operator: A shorthand if-else statement that performs a quick inline evaluation and returns one of two values (e.g., condition ? valueIfTrue : valueIfFalse).
Iteration Statements (Loops)
Allow code blocks to run multiple times until a condition is met.
for loop: Has three parts: initialization, condition, and increment/decrement (e.g., for (let i = 0; i < 10; i++) { … }). Often used to iterate a fixed number of times or through arrays using length.
while loop: Continues to execute as long as a specified condition is true. More flexible, as the iteration control can be embedded within the loop’s body.
break: Exits a loop or switch statement immediately.
Objects
An object stores related properties (attributes) of a single data element.
Object Literal Syntax: Defined using curly braces {} with name: value pairs for properties and methods.
Properties: Named values that define characteristics (e.g., make: ‘BMW’).
Methods: Functions defined inside an object (e.g., printDescription: function() { … }).
Accessing Properties/Methods: Use dot notation (object.property) or bracket notation (object[‘property’]). Dot notation is generally preferred.
Objects can be dynamically modified (properties added/removed).
Can contain complex structures like nested objects or arrays of objects.
Related to JSON (JavaScript Object Notation), a common format for data exchange, with very similar but not identical syntax to object literals.
Arrays
A variable that can hold many different values (a list of information).
Declared using square brackets [] with comma-separated values (e.g., let a =).
Elements are zero-indexed (first element is at index 0).
Can hold elements of different data types within the same array.
length property: Returns the number of elements in the array (not zero-indexed).
Common Array Methods:
push(): Adds one or more elements to the end.
pop(): Removes the last element.
shift(): Removes the first element.
unshift(): Adds one or more elements to the beginning.
concat(): Combines two or more arrays.
join(): Joins all elements into a single string, with an optional separator.
reverse(): Reverses the order of elements.
sort(): Sorts the elements (lexicographically for strings, numerically for numbers).
indexOf(): Returns the first index at which a given element can be found.
lastIndexOf(): Returns the last index at which a given element can be found.
map(): Creates a new array by calling a function on every element of the original array.
filter(): Creates a new array with all elements that pass a test implemented by a provided function.
forEach(): Executes a provided function once for each array element.
every(): Checks if all elements in an array pass a test.
some(): Checks if at least one element in an array passes a test.
Error Handling
JavaScript’s runtime will throw an exception and quit if it encounters something it cannot work with.
try-catch-finally: A construct to safeguard code.
try: Contains code that might throw an exception.
catch: Executes if an exception is thrown in the try block, allowing you to handle the error (e.g., inspect the Error object’s message property).
finally: Executes regardless of whether an exception occurred or was caught, typically for cleanup.
Throwing Custom Errors: You can use throw new Error(“message”) to communicate failures from a function to its caller.
Advanced Topics (Introduced as Basics)
this Keyword: Represents the context in which a function is called, and its value depends on how the function is invoked (e.g., globally, as an object method, using call() or apply()). In a web browser, this can refer to the window object (global context) or the DOM element that triggered an event.
Destructuring: A syntax for “unpacking” values from arrays or properties from objects into distinct variables or other array/object elements.
Template Literals: Use backticks (`) to create strings that can span multiple lines and embed expressions using ${expression} (interpolation).
Regular Expressions (Regex): Patterns used to search, match, and manipulate strings. While complex, basic use involves creating patterns (/pattern/) and using string methods like test() (checks for match), replace() (replaces matches), and match() (returns match details).
Built-in Natives (Primitive Wrappers): Primitive types like string, number, and boolean have corresponding built-in “native” functions (e.g., String, Number, Boolean) that return objects with rich sets of methods. JavaScript automatically “boxes” (wraps) primitives into these objects when methods are called and “unboxes” them back to primitives.
Constructor Functions: Normal functions that, when called with the new keyword, create and initialize a new object instance. The new keyword binds the newly created empty object to this inside the constructor function. Constructor functions are conventionally named with an uppercase first letter.
Prototype Chain (Prototypal Inheritance): JavaScript’s mechanism for inheritance. Objects can link to other objects (prototypes), forming a chain. When a property or method is accessed on an object, JavaScript searches up this chain until it finds the definition.
Classes: Introduced in modern JavaScript as syntactic sugar over the existing object and prototype models. They provide a more familiar class-like syntax (class Car { constructor() {} method() {} }) but internally still rely on prototypes. They can extend other classes to approximate inheritance.
Closures: Allow a function to “remember” and access variables from its outer (lexical) environment even after the outer function has finished executing. Each closure creates its own “lexical environment”.
Truthy and Falsy Values: JavaScript evaluates certain values as true (truthy) or false (falsy) in a boolean context, even if they are not explicitly boolean. Examples of falsy values include false, null, undefined, 0, NaN, and empty strings (”, “”). Everything else is generally truthy.
JavaScript in Web Browsers (DOM)
The Document Object Model (DOM) is an object-based representation of an HTML page, allowing programmatic access and manipulation of elements, their attributes, and text.
Web browsers construct the DOM by parsing HTML, applying CSS styles, and processing JavaScript.
JavaScript can interact with the DOM to:
Access nodes: Using methods like document.getElementById().
Change attributes: Modify properties of DOM elements (e.g., element.style.fontSize).
Add/Remove nodes dynamically: Create new elements (document.createElement()) and append them (element.appendChild()) or remove them.
Associate event handlers: Attach functions to respond to user interactions (e.g., element.addEventListener(‘click’, function)).
It’s generally recommended to keep JavaScript in separate .js files and link them in the HTML using <script src=”file.js”></script> at the bottom of the <body> to ensure DOM elements are loaded before scripts try to access them. Inline JavaScript in HTML attributes (like onclick) or <script> tags in the <head> is generally frowned upon for professional development.
JavaScript Variables and Scope Fundamentals
In JavaScript, understanding variables and their scope is fundamental to writing effective and maintainable code.
Variables
A variable is essentially a named area in the computer’s memory where you can store and retrieve values throughout the lifespan of your application.
JavaScript offers several keywords for declaring variables:
let: This is the recommended keyword for declaring variables in modern JavaScript. It allows you to express your intent to create a new variable.
var: This was the original keyword for variable declaration. Its usage can be nuanced and may lead to unexpected behaviors, particularly concerning scope, which can be challenging for beginners. It’s generally advised to abandon var unless specifically required.
const: This keyword is used when you intend for a variable’s value never to change after its initial assignment. Attempting to reassign a const variable will result in an error.
Variable Assignment and Initialization: The equal sign (=) is the assignment operator, used to assign a value to a variable. When you declare a variable but do not immediately assign it a value, its value is undefined. This is known as declaration without definition. It’s generally preferable to initialize your variables at the moment of declaration if possible.
Naming Rules for Variables (Identifiers): There are strict rules for naming variables (also called identifiers) that, if violated, will cause your application to break:
All identifiers must begin with a letter, a dollar sign ($), or an underscore (_).
Variable names can contain letters, numbers, dollar signs, or underscores, but no other special characters or spaces.
You cannot use JavaScript keywords as variable names (e.g., let cannot be a variable name).
Variable names are case-sensitive (e.g., x and X are treated as two different variables).
Code Conventions for Variables (Best Practices): These are not enforced by the JavaScript compiler but are highly recommended for readability and collaboration:
Descriptive names: Use names that clearly indicate the purpose or meaning of the data being stored (e.g., firstNumber instead of x).
Camel casing: For multi-word variable names, the first word should be lowercase, and subsequent words should start with a capital letter (e.g., firstName, zipCode).
Consistency: Maintain a consistent naming style throughout your application.
Do not rely on case: Avoid using variable names that differ only by case if they refer to conceptually the same thing, as this can introduce subtle confusion and programming errors (e.g., zipCode and zipcode as distinct variables should be avoided).
Data Types and Variables: It’s important to note that variables themselves do not have a data type; only the values stored inside the variables have a data type. Common data types include number, boolean, string, undefined, object, and function.
Scope
Scope refers to the lifespan and availability of variables and functions within your application. Variables are like people; they have a lifespan (born, do work, die) and a “citizenship” determining where they can be accessed. When a code block finishes executing, variables defined within that block are typically removed from the computer’s memory, meaning they go “out of scope”.
Fundamental Rules of Scope:
A variable declared in an outer (parent) code block (scope) is visible and accessible within all inner (child) code blocks that it encloses.
Conversely, a variable declared in an inner (child) code block is not available to outer (parent) scopes once that inner block has finished executing.
Variables declared in an outer scope can have their values changed by code within inner scopes.
Global Scope: The global scope is the topmost level of scope in JavaScript. While less of an issue in Node.js applications, defining variables and functions in the global scope is a crucial concern and generally considered a bad idea in web development:
Memory Consumption: Each variable defined in the global scope remains in the computer’s memory until the web browser tab navigates to a new page, potentially consuming significant memory over time.
Naming Collisions: When multiple JavaScript files (your code, libraries, third-party scripts) are loaded on a single web page, defining variables and functions in the global scope increases the likelihood of “naming collisions.” This occurs when two different scripts define variables or functions with the same name, leading to one overwriting the other, causing unanticipated and difficult-to-track bugs.
The var keyword, unlike let or const, specifically attaches variables to the global scope (e.g., the window object in a web browser’s Document Object Model, or DOM). Therefore, let is recommended to avoid polluting the global scope.
Solutions to Global Scope Issues (Module Pattern): To mitigate global scope problems, especially in web development, the Module Pattern is a widely used design pattern. This technique employs an Immediately Invoked Function Expression (IIFE) that returns an object.
It allows you to define private variables and functions that are not directly accessible from outside the module, promoting encapsulation (hiding implementation details).
The IIFE then returns an object containing “public” properties and methods, which are the only parts exposed to the outside world.
This significantly reduces the impact on the global scope by consolidating many internal variables and functions under a single, unique module variable.
The Revealing Module Pattern is a variation that explicitly lists the public properties and methods within the returned object, offering a cleaner presentation of what is exposed.
Closures (A Related Concept): Closures are a powerful JavaScript concept related to scope. A closure allows a function to remember and access variables from its surrounding lexical environment (the scope in which it was declared), even after that outer function has finished executing.
Essentially, it associates some data with a function at the time the function is created.
Each closure creates its own lexical environment, meaning it gets its own set of variables and input parameters from its enclosing scope. This allows for functions that are “pre-filled” with certain data based on when and where they were defined and returned.
The this Keyword (Contextual Binding): The meaning of the this keyword in JavaScript is not fixed; it represents the way a given function is called, and its value changes based on the context of that call.
Global Context: When a function is called directly in the global scope (not as a method of an object or with explicit binding), this refers to the global object (e.g., global in Node.js, or window in a web browser).
Strict Mode: If “use strict” is enabled, calling a function in the global context will cause this to be undefined instead of the global object.
Object Methods: When a function is invoked as a method of an object (e.g., myObject.myMethod()), this inside that method refers to the object itself (myObject in this example). This allows methods to access the object’s properties (e.g., this.propertyName).
Explicit Binding (call() and apply() methods): Functions in JavaScript have built-in methods, call() and apply(), that allow you to explicitly set the value of this for that function call. The difference between call() and apply() lies in how additional arguments are passed: call() takes them individually, while apply() takes them as an array.
DOM Event Handlers: In web browsers, when a function is called from an inline event handler (e.g., onclick=”myFunction(this)”), the this passed as an argument within the HTML refers to the DOM element itself. However, if the handler function itself is defined without explicit binding, the this inside that function will default to the global window object.
Understanding variables and how their scope impacts their availability and behavior is crucial for developing robust JavaScript applications.
JavaScript: Functions, Objects, and Their Interrelation
In JavaScript, functions and objects are core building blocks for structuring and organizing code. They work together to create dynamic and interactive applications.
Functions
A function is a named block of code that can be repeatedly executed throughout your application. Functions serve as a primary construct in JavaScript for accomplishing tasks.
Function Declaration vs. Function Expression:
A function declaration uses the function keyword followed by a name (identifier). For example, function sayHello() { … }. Function declarations are “hoisted” to the top of their execution environment, meaning they can be called before they are defined in the code.
A function expression is typically an anonymous function (without a name) assigned to a variable. For example, let myFunc = function() { … }. These are often used when a function is needed as an argument to another function or when it’s only called once.
Arrow Functions:
Introduced in recent JavaScript versions, arrow functions (=>) provide a shorthand syntax for defining functions. They remove the need for the function keyword and use a “fat arrow” to point to the function body.
They can accept input parameters within parentheses and have a body defined by curly braces.
Arrow functions are especially useful for concise, inline functions, such as when iterating over arrays with methods like map(), filter(), or forEach().
Key Aspects of Functions:
Arguments (Input Parameters): Functions can accept data (arguments) passed into them, which can then be used within the function’s body.
Return Values: Functions can return a single value back to wherever they were called using the return keyword. This value can be any data type, including another function.
Functions as Data Types: In JavaScript, functions are considered a data type themselves. This means they can be assigned to variables, passed as arguments to other functions, and even returned as values from other functions.
Immediately Invoked Function Expressions (IIFEs): An IIFE is a function expression that is executed immediately after it’s defined. It’s typically wrapped in parentheses and then followed by another set of parentheses to invoke it. IIFEs are a common pattern in JavaScript development, particularly for controlling scope and avoiding global variable pollution.
Objects
An object is a container that holds related properties and methods (functions) of a single data element. Unlike arrays, which hold lists of multiple data elements, an object defines the characteristics and behaviors of one specific item.
Creating Objects:
Object Literal Syntax: This is the most common way to create an object, using curly braces {} to define a collection of name-value pairs (properties) and functions (methods). For example, let car = { make: “BMW”, model: “745li”, year: 2010 };.
Constructor Functions: A constructor function is a regular JavaScript function that is intended to be called with the new keyword. The new keyword creates an empty object, sets it as the this context for the function call, and then the function populates this new object with properties and methods. A convention is to name constructor functions with an uppercase first letter to indicate their intended use with new.
Classes (ES6): Introduced as “syntactic sugar” in the latest JavaScript versions, class provides a more familiar structure for defining objects, resembling traditional object-oriented programming (OOP) languages like Java or C#.
A class can have a special constructor method that is automatically called when a new instance of the class is created using new.
Methods can be defined directly within the class body.
The extends keyword allows a class to “inherit” from another class, providing properties and methods from the parent class to the child class. Despite the class and extends keywords, JavaScript still operates on its underlying prototype model for “inheritance”.
Key Aspects of Objects:
Properties and Methods: Properties are named values that describe the object (e.g., car.make), while methods are functions associated with the object that define its behavior (e.g., car.printDescription()).
Accessing Members: Properties and methods are typically accessed using dot notation (.) (e.g., car.make, car.printDescription()). Bracket notation (car[‘make’]) can also be used, though dot notation is generally preferred.
Dynamic Nature: Objects in JavaScript are dynamic; properties and methods can be added or even deleted from an object after it has been created.
Object Graphs: Objects can contain other objects or arrays of objects, forming complex data structures known as “object graphs”.
JSON (JavaScript Object Notation): JSON shares a very similar syntax with JavaScript object literals, making it a popular format for data interchange between systems.
Interrelation and Key Concepts
Functions and objects are deeply intertwined in JavaScript:
The this Keyword: This is a crucial concept, as this represents the context in which a function is called, and its value changes dynamically.
When called in the global context, this refers to the global object (e.g., window in browsers, global in Node.js).
When a function is invoked as a method of an object (e.g., myObject.myMethod()), this inside that method refers to the object itself (myObject). This allows methods to access the object’s properties (e.g., this.propertyName).
The call() and apply() methods allow you to explicitly set the value of this for a function call.
In DOM event handlers, this typically refers to the DOM element on which the event listener is defined.
Scope and Module Pattern: Functions are fundamental to controlling variable scope. The Module Pattern, which often utilizes an IIFE that returns an object, is a widely used design pattern to encapsulate private variables and functions and expose only “public” ones through a single object, thereby reducing global scope pollution and naming collisions.
Closures: Closures are a powerful feature where a function “remembers” and can access variables from its surrounding (lexical) environment even after the outer function has finished executing. This allows a function to be pre-filled with specific data from its creation context.
Built-in Natives: JavaScript’s primitive data types (like string, number, boolean) have corresponding “built-in native” constructor functions (e.g., String(), Number()) that return objects. The JavaScript compiler automatically “boxes” primitives into these native objects to provide them with a rich set of methods (e.g., string.toLowerCase()), and “unboxes” them back as needed. Arrays and regular expressions are also built-in natives that are objects and come with their own sets of methods.
JavaScript Control Flow: Logic, Loops, and Error Handling
In JavaScript, control flow refers to the order in which individual statements, instructions, or function calls are executed. By default, JavaScript statements execute sequentially from top to bottom within a file. However, various constructs allow developers to alter this default sequential execution, introducing logic, repetition, and error handling into their applications.
Basic Building Blocks of Code
Statements: A statement is one complete instruction to the JavaScript compiler, similar to a sentence in English. Each JavaScript file typically contains one or more statements that usually execute in sequential order.
Expressions: Statements are composed of one or more expressions, which are in turn made up of operators and operands. Operators are keywords or symbols (like +, =, let), while operands are values or identifiers (like variable names or function calls). Combining operators and operands creates expressions that perform actions or evaluations.
Categories of Control Flow
JavaScript provides several categories of control flow mechanisms:
Sequential Execution By default, JavaScript code runs from the first line to the last line. This is the simplest form of control flow.
Decision Statements Decision statements allow you to perform different blocks of code based on whether a certain condition evaluates to true or false. JavaScript treats certain values as “truthy” (evaluating to true) or “falsy” (evaluating to false) even if they are not explicitly true or false booleans. For example, null, undefined, 0, NaN, and empty strings (“”, ”) are considered falsy, while an empty object ({}), an empty array ([]), non-empty strings, and any non-zero number are truthy.
if / else if / else: This is the most common decision statement.
An if statement evaluates an expression; if it’s true, the code block associated with it is executed.
You can include optional else if statements to evaluate other expressions if the preceding if or else if conditions were false.
An else statement acts as a catch-all, executing its code block if none of the preceding if or else if conditions were true.
switch Statement: The switch statement evaluates a single expression against a number of case values.
If a case matches the expression’s value, the code block under that case is executed.
Without a break statement, execution will “flow through” to subsequent case blocks, including the default case if present. The break statement is used to exit the switch block after a match is found.
A default case can be provided to handle situations where none of the case values match.
Ternary Operator (? 🙂: This provides a concise, inline way to perform a quick evaluation and return one of two values.
It consists of an expression, followed by a question mark (?), then the value to return if the expression is true, a colon (:), and finally the value to return if the expression is false.
For example, doesAEqualB ? “equal” : “not equal”.
Equality Operators: The source discusses both loose equality (==) and strict equality (===). Loose equality performs type coercion before comparison (e.g., 7 == “7” is true), while strict equality checks both value and data type without coercion (e.g., 7 === “7” is false). Similar operators exist for inequality (!= and !==).
Iteration Statements (Loops) Iteration statements allow a block of code to be executed repeatedly until a specified condition is met.
for Loop: A for loop is typically used when you know the number of iterations or want to iterate over a sequence using an index. It has three parts:
Initialization: Declares and initializes a counter variable (e.g., let i = 0).
Condition: An expression that is evaluated before each iteration; the loop continues as long as this condition is true (e.g., i < 10).
Increment/Decrement: An operation performed after each iteration to update the counter (e.g., i++).
for loops are often used to iterate through arrays, accessing elements by their index.
while Loop: A while loop continues to execute its code block as long as a given condition remains true.
It is more flexible than a for loop because the iteration logic (like incrementing a counter or reading to the end of a file) is controlled within the loop’s body, not just in its header.
The break statement can be used within both for and while loops to immediately exit the loop, regardless of the loop’s condition.
Error Handling JavaScript applications can encounter “exceptions” or “errors,” which are situations that prevent the code from continuing execution. When an exception occurs, the JavaScript runtime will “quit” at that point, stopping any further code execution.
try-catch-finally: This construct allows you to safeguard code that might throw an exception.
The try block contains the code that is susceptible to throwing an exception.
If an exception occurs within the try block, execution immediately jumps to the catch block, which receives an “error object” containing information about the exception (e.g., error.message). This prevents the application from completely shutting down.
The finally block will execute regardless of whether an exception occurred or was caught. It’s often used for cleanup operations.
Throwing Custom Exceptions: Developers can explicitly throw a new Error object from their functions to communicate failure to the caller. This allows the calling code to implement contingency or retry logic.
JavaScript Data Types and Coercion
In JavaScript, data types are essentially a description of the kind of data you want to store and what you intend to do with it. Unlike some other programming languages, variables themselves do not have a data type; only the values stored inside the variables have data types.
JavaScript categorizes its data types into several fundamental types:
Primitive Data Types
The core primitive data types discussed include:
Number: Used for any positive or negative numbers, including decimal values. If you want to perform math or algebraic operations, you should use a number.
Boolean: Represents true or false values. These are the only two possible values for a boolean.
String: Represents a sequence of characters. Strings are typically enclosed in single quotes (”) or double quotes (“”). They are often used to display content on the screen.
Undefined: This type indicates that a variable has been declared but no value has been assigned or initialized to it. When a variable is undefined, its value is undefined, and its type is also undefined. It’s different from null because undefined implies an expected value was never set, whereas null means an object reference was expected but is currently pointing to nothing.
Null: Represents a variable that points to nothing, specifically when an object reference was expected. While its value is null, a known quirk in JavaScript is that typeof null returns “object”, not “null”. This is a known bug that is unlikely to be fixed due to existing code dependencies. It is not zero, undefined, or an empty string.
Other Data Types
Object: This is a more complex data type. An object contains the related properties (attributes) and methods of a single data element, contrasting with an array which holds a list of many data items. Arrays themselves are considered a type of object (typeof an array returns “object”). Objects can hold properties of various data types, including other objects or arrays.
Function: Functions are considered their own data type in JavaScript. A reference to a function, when its invocation operator () is not used, will reveal its type as function.
The typeof Operator
The typeof operator can be used to determine the data type of a value. For example, typeof x will output the data type of the value currently stored in x.
Type Coercion
JavaScript can sometimes automatically convert one data type into another in certain operations, a process known as coercion. This can lead to unexpected results.
For instance, the plus operator (+) performs double duty: it can be the addition operator for numbers or the string concatenation operator for strings.
If you attempt to “add” a number and a string (e.g., 7 + “6”), JavaScript will coerce the numeric value into a string and then concatenate the two strings (resulting in “76”).
To force a string to be treated as a number for arithmetic operations, you can use built-in functions like parseInt(). parseInt() takes a string and an optional radix (base system, e.g., 10 for decimal) to convert the string into an integer.
If a string cannot be converted into a numeric value, parseInt() (or other numeric conversion attempts) might return NaN (Not a Number), which is a special numeric value indicating an invalid or unrepresentable number.
Primitive Types and Built-in Natives
JavaScript provides “built-in native” functions (or constructors) for primitive types like String, Number, and Boolean, distinguished by their uppercase first letter.
These native functions return objects that provide a rich set of methods and properties (e.g., value.replace() for strings, string.toLowerCase(), string.length).
When you use a primitive value (like a literal string “howdy”) and call a method on it (e.g., “howdy”.toLowerCase()), the JavaScript compiler coerces or “boxes” that primitive into its corresponding built-in native object behind the scenes to provide the method, and then “unboxes” it back into a primitive when needed, without explicit developer intervention.
You can explicitly create instances of these native objects using the new keyword (e.g., new String(“howdy”)), and then use the .valueOf() method to convert them back into their primitive equivalents. However, it is generally recommended to stick with using the primitive types and let JavaScript handle the boxing and unboxing automatically.
Truthiness and Falsiness
In decision statements (like if or switch), JavaScript evaluates expressions to determine if they are “truthy” or “falsy”.
Falsy values are those that, when evaluated in a boolean context, are treated as false:
false
null
undefined
0 (the number zero)
NaN (Not a Number)
“” or ” (empty strings)
Truthy values are all other values that are not explicitly falsy, meaning they evaluate to true in a boolean context:
true
Empty objects ({})
Empty arrays ([])
Non-empty strings
Any non-zero number (integers or floats)
Infinity (positive or negative)
Javascript tutorial for beginners Full course | javascript Full crash course for Beginners
Affiliate Disclosure: This blog may contain affiliate links, which means I may earn a small commission if you click on the link and make a purchase. This comes at no additional cost to you. I only recommend products or services that I believe will add value to my readers. Your support helps keep this blog running and allows me to continue providing you with quality content. Thank you for your support!
The provided text explains the Fetch API in JavaScript, a crucial tool for web development that enables data exchange between applications and servers. It details how the fetch() function sends requests (often including URLs, methods, and headers) to an API and receives a response object, which typically needs to be converted to JSON for practical use. The explanation also covers asynchronous operations with async/await for handling promises returned by Fetch, demonstrates how to incorporate API tokens for authentication, and distinguishes between Fetch operation failures and server-side errors, emphasizing the importance of proper error handling. Finally, the text briefly touches on the history of Fetch and its advantages over older methods like XMLHttpRequest (XHR).
The Fetch API: Web Data Requests
The Fetch API is a fundamental JavaScript function used for making network requests to retrieve or send data over the web. It is one of the primary native ways to handle the back-and-forth exchange of data between web applications and servers or APIs, which is crucial for the web’s functionality.
Here are the basics of the Fetch API:
Core Mechanism: The fetch API operates on a simple “ask and you shall receive” model: you send a request and receive a response.
Requesting Data:
To initiate a request, you call the fetch function, primarily passing the URL of the API you want to access. This URL can point to any publicly accessible API.
When you provide only a URL string, JavaScript automatically creates a Request object for you behind the scenes. This Request object defaults to the GET method and sets other properties to their default values.
For more complex requests (e.g., sending data, specifying headers like API tokens), you can explicitly create a Request object and pass it to fetch.
Asynchronous Operation:
fetch is an asynchronous operation because it involves a round trip to a server, which takes time.
Instead of directly returning the response, fetch returns a Promise. This Promise will eventually resolve into a Response object once the network request is complete.
To handle this asynchronous nature and wait for the Promise to resolve, you typically use async/await or .then()/.catch() blocks.
The Response Object:
The Response object that fetch resolves into contains metadata about the server’s reply. This includes information like the URL called, the HTTP status code (e.g., 200 for success, 401 for unauthorized), and an ok property indicating if the request was successful.
Crucially, the initial Response object does not directly contain the actual data you requested (like the time, news articles, or band information).
To extract the actual data, especially if it’s in JSON format (which is common for front-end APIs), you must call the .json() method on the Response object.
The .json() method itself is also an asynchronous operation and returns a Promise, meaning you need to await its completion to get the parsed data.
Native and Modern: fetch is a native function built into JavaScript in modern browsers and has been natively supported in Node.js version 18 and later since April 2022. It is often preferred over older methods like XML HTTP Request (XHR) because its Promise-based interface leads to cleaner and more readable code.
Fetch API: Requests, Responses, and Data Handling
In the context of the Fetch API, the Request and Response objects are fundamental to how data is sent and received over the web. The basic mechanism of fetch involves sending a request and receiving a response.
The Request Object
When you use the fetch API, you are essentially creating and sending a Request object.
Implicit Creation: If you simply pass a URL string to the fetch function (e.g., fetch(‘https://api.example.com/data’)), JavaScript automatically creates a Request object for you behind the scenes. In this default scenario, the Request object’s URL is set to the provided string, and other properties like the method are set to their default values, which for the method is GET. This is suitable for simple data retrieval.
Explicit Creation: For more complex scenarios, such as sending data, specifying different HTTP methods (like POST), or adding custom headers (like API tokens), you need to explicitly create a Request object.
You create a new Request object using new Request().
The first parameter is the URL.
The second parameter is an object containing additional configuration, such as:
method: To specify GET, POST, PUT, etc..
headers: An object containing key-value pairs for HTTP headers. This is crucial for authentication (e.g., sending an Authorization header with an access token for the Spotify API) or specifying content types.
body: For requests that send data to the server (like POST requests), the body property is where you add the data you need to pass to the server, such as form submissions.
cache policy: Controls how the request interacts with the browser’s HTTP cache.
Parameters:
For GET requests, parameters are typically sent as URL parameters (query strings like ?param=value).
For requests like POST, data is often sent in the request body.
The Response Object
After fetch sends a request, it returns a Promise that will eventually resolve into a Response object.
Asynchronous Nature: fetch is an asynchronous operation because it involves a network request to a server, which takes time. Therefore, it returns a Promise, and you typically use async/await or .then() to handle its resolution.
Contents of the Response Object: The Response object itself contains metadata about the server’s reply, but not the actual data you’re looking for. Key properties include:
url: The URL that was called.
status: The HTTP status code (e.g., 200 for success, 401 for unauthorized, 404 for not found). This indicates the outcome of the server’s processing of your request.
ok: A boolean property (true or false) that indicates if the HTTP response status code was in the range 200-299, signifying a successful response. This is often used for error checking.
headers: An object containing the HTTP headers returned by the server.
body: This property exists but does not directly expose the data in a usable format.
Extracting Data from the Response: To get the actual data (e.g., time information, news articles, band details), you must call specific methods on the Response object, most commonly .json() for APIs that return data in JSON format.
The .json() method is also an asynchronous operation and returns a Promise, meaning you need to await its completion to get the parsed JavaScript object.
Other methods exist for different data types (e.g., .text() for plain text, .blob() for binary data).
Error Handling:
It’s important to understand that a fetch operation is considered successful (the Promise resolves) if it successfully makes a trip to the API and receives any response, even if that response indicates an error (e.g., a 401 or 404 status code).
The fetch Promise will only reject (leading to a .catch() block or try/catch around await fetch) if there’s a network error (e.g., unable to connect to the server).
Therefore, to handle server-side errors (like a 401 “no token provided”), you must explicitly check the response.ok property or response.status code after the fetch Promise resolves, before attempting to process the data.
Fetch API Error Handling Demystified
Error handling with the Fetch API is a critical aspect of building robust web applications, as it requires distinguishing between different types of failures.
Here’s a breakdown of error handling with Fetch:
Fetch Promise Resolution vs. Rejection
A key concept to understand is how the fetch Promise behaves:
The fetch function returns a Promise that will resolve if it successfully makes a trip to the API and receives any response, even if that response indicates a server-side error (like a 401 or 404 HTTP status code). This means that if you use async/await, your code will continue past await fetch(…) even if the server returns an error code. If you’re using .then()/.catch() syntax, the .then() block will still execute.
The fetch Promise will only reject (triggering a catch block in try…catch or a .catch() in a Promise chain) if there’s a network error (e.g., the browser is unable to connect to the server, or the URL is completely unresolvable). For example, trying to fetch from a “fake banana Republic” URL will result in a “failed to fetch” error that lands in the catch block because the request couldn’t even be completed.
Distinguishing Between Error Types
Due to this behavior, you need to handle two distinct types of errors:
Network Errors: These occur when the fetch operation itself fails to complete, typically because it couldn’t reach the server.
How to Handle: These errors cause the fetch Promise to reject. You can catch them using a try…catch block (with async/await) or a .catch() method (with Promises).
Example: If you attempt to fetch from a non-existent domain like “banana pudding,” the operation will fail to connect, and the error will be caught, often indicating “failed to fetch”.
Server-Side Errors (HTTP Errors): These occur when the fetch operation successfully connects to the server and receives a response, but the response’s HTTP status code indicates an error (e.g., 4xx client errors or 5xx server errors).
Response Properties: The Response object contains properties to help you identify these errors:
response.status: This provides the HTTP status code (e.g., 200 for OK, 401 for Unauthorized, 404 for Not Found).
response.ok: This is a convenient boolean property (true or false) that indicates if the HTTP response status code was in the range 200-299 (i.e., a successful response). If response.ok is false, it means the server returned an error status.
How to Handle: Since these errors don’t cause the fetch Promise to reject, you must explicitly check the response.ok property or response.status codeafter the fetch Promise resolves. If response.ok is false or response.status is not 200, you know it’s a server-side error. You can then choose to throw your own error or handle it as needed.
Practical Implementation of Error Handling
A robust approach combines both try…catch for network issues and conditional checks for server responses:
// If response.ok is true, proceed to parse the actual data
const data = await response.json();
console.log(“Success! Data received:”, data);
} catch (error) {
// This block catches network errors or any errors explicitly thrown above
console.error(“Fetch operation failed (network error or custom error):”, error.message);
}
}
getData();
This structure ensures that you:
Catch network failures immediately using try…catch.
Explicitly check for and handle server-reported errors (e.g., 401 “no token provided” from the Spotify API, which will resolve but have response.ok as false) before attempting to process the data.
Can extract and display more specific error messages from the server’s response body if it returns JSON with error details.
API Authentication Methods and Best Practices
API authentication is crucial for controlling access to data and services provided by APIs, often to prevent abuse and track usage. When a web application needs to interact with a backend API, it often needs to prove its identity or authorization to access specific resources.
Here’s a breakdown of API authentication methods discussed:
Purpose of Authentication:
Many APIs, even “free” ones, need to limit how many times they are called to prevent users from abusing the service.
It helps API maintainers know who is calling their API and how many times, as running an API still incurs costs.
API tokens act like a “password” or “signature” to identify the caller.
Some APIs require users to create an account before they can be used.
API Tokens:
API tokens are a common mechanism for authentication.
They are often long strings of numbers and letters.
Methods for Sending Authentication Data:
URL Parameters:
For GET requests, parameters, including API tokens, can sometimes be sent directly in the URL as query parameters.
This is done using a question mark (?) followed by parameterName=value (e.g., ?api_token=your_token_value).
While possible, this method is not considered very secure for sensitive data like tokens.
Request Headers:
For a more secure way to send parameters, especially sensitive ones like API tokens, APIs often require them to be sent in HTTP headers.
This requires you to explicitly create a Request object when using the Fetch API, rather than just passing a URL string.
The Request object takes the URL as the first parameter and an object containing additional configuration (like headers) as the second parameter.
Example: Spotify API: The Spotify API requires an Authorization header with an “access token”. You would typically set this up as part of the Request object:
new Request(URL, {
headers: {
Authorization: ‘Bearer YOUR_ACCESS_TOKEN’ // ‘Bearer ‘ is often a prefix
}
});
.
Access tokens can expire, meaning you might need to obtain a new one if a previously used token is no longer valid.
Authentication-Related Errors:
When an API requires authentication (like a token) and it’s missing or invalid, the server will often return an HTTP status code indicating an error.
A common error is 401 Unauthorized (e.g., “no token provided” or “invalid access token”).
It’s important to remember that fetch considers a 401 response a successful call in terms of network connection, meaning the Fetch Promise will resolve, not reject. The Promise only rejects if there’s a network issue and the server cannot be reached at all.
Therefore, you must explicitly check the response.ok property or response.status code after receiving the response to determine if the authentication was successful or if the server reported an error.
Fetch API Versus XHR: Modern JavaScript HTTP Requests
Both Fetch API and XML HTTP Request (XHR) are native JavaScript mechanisms for making HTTP requests to servers, enabling web applications to send and receive data. While they achieve the same fundamental goal, Fetch is generally preferred in modern web development due to its more intuitive and cleaner interface.
Here’s a comparison:
XML HTTP Request (XHR)
History: XHR is an older, “old school” way of making HTTP requests that predates Fetch.
Mechanism: It is callback-based, meaning you attach functions that get executed when certain events occur (e.g., onload, onerror).
Drawbacks: XHR is often described as “ugly” and “messy”. Its callback-based nature can lead to less readable and more complex code, particularly when dealing with multiple asynchronous operations (often referred to as “callback hell”).
Fetch API
Arrival: Fetch arrived in modern browsers between 2015 and 2017. Node.js version 18 and later also added native support for Fetch as of April 2022.
Mechanism: Fetch is Promise-based. This means fetch returns a Promise that resolves into a Response object. This design integrates well with modern asynchronous patterns like async/await, making the code more synchronous-looking and easier to read and manage.
Advantages:
Simpler Interface: Fetch offers a nicer interface compared to XHR. For simple GET requests, you can just pass the URL as a string, and JavaScript automatically creates a Request object with default settings.
Readability: Its Promise-based nature, especially when combined with async/await, leads to cleaner and more manageable asynchronous code.
Request/Response Objects: Fetch explicitly uses Request and Response objects, which have various properties and methods for configuring requests and processing responses (e.g., response.json() to parse JSON data).
Error Handling: While fetch’s Promise resolves even on HTTP error status codes (like 401 or 404), it provides properties like response.ok and response.status to easily check for server-side errors, allowing developers to handle these distinct from network failures which reject the Promise. (This differs from older callback models where handling various states could be more cumbersome).
When to use: Generally, if you can do something natively in JavaScript, you probably should, and Fetch supports most cases for modern applications.
Key Differences and Preference
The primary reason to prefer Fetch over XHR is its Promise-based design, which simplifies asynchronous operations and leads to more readable code. While both are native ways to make HTTP requests, Fetch offers a significantly improved syntax and developer experience. Both can be observed in browser developer tools under the Network tab, with filters specifically for “xhr” and “fetch” requests.
Affiliate Disclosure: This blog may contain affiliate links, which means I may earn a small commission if you click on the link and make a purchase. This comes at no additional cost to you. I only recommend products or services that I believe will add value to my readers. Your support helps keep this blog running and allows me to continue providing you with quality content. Thank you for your support!
This text provides excerpts from the second edition of the ASP.NET jQuery Cookbook, originally published in 2011 and updated in 2016 by Packt Publishing. It serves as a practical guide with recipes for integrating jQuery with ASP.NET web forms and MVC applications. Key topics covered include setting up and managing jQuery libraries, utilizing jQuery selectors to interact with controls, handling various events, manipulating the Document Object Model (DOM), adding visual effects, and performing Ajax calls. The book also guides readers on creating and using jQuery plugins, including leveraging NuGet for package management and debugging techniques within Visual Studio.
Based on the provided sources, here is a discussion about jQuery:
jQuery is a lightweight JavaScript library that has transformed the landscape of client scripting in web applications. Developed by John Resig in 2006, it quickly gained popularity due to its cross-browser compatibility and its ability to “get more done with less code”. The library is supported by an active community of developers and has grown significantly. Using jQuery simplifies many client scripting tasks, including event handling, embedding animations, and writing Ajax-enabled pages, contributing to a more interactive experience for the end-user. Its extensible plugin architecture also allows developers to build additional functionalities on top of the core library.
The library consists of a single JavaScript (.js) file. At the time the source was written, jQuery was available in two major versions: Version 1.x and Version 2.x. While the Application Programming Interface (API) is the same for both, Version 2.x does not support older browsers like IE 6, 7, and 8, whereas Version 1.x continues to support them. You can download jQuery in either uncompressed format (for development and debugging) or compressed format (for production, also known as the minified version). The minified version uses optimization techniques like removing whitespaces and shortening variable names, making it smaller but harder to read. A map file (.min.map) is available to simplify debugging of the minified version by mapping it back to its unbuilt state.
Including jQuery in an ASP.NET application can be done in several ways:
Downloading from jQuery.com and manually adding the file to your project.
Using a Content Delivery Network (CDN), which hosts the jQuery library on distributed servers. This can improve performance as users might already have the file cached from visiting other sites that use the same CDN. Available CDNs include jQuery’s CDN, Google CDN, Microsoft CDN, CDNJS CDN, and jsDelivr CDN. Using a CDN means linking directly to the library file hosted online instead of using a local copy. Note that CDNs might take a couple of days to update with the latest jQuery releases.
Using the NuGet Package Manager, available with Visual Studio, which simplifies installing and upgrading the library within your project. NuGet typically downloads the debug (.js), release (.min.js), Intellisense (.intellisense.js), and map (.min.map) files into the project’s Scripts folder.
Adding jQuery to an empty ASP.NET web project using a script block (<script>) by referencing the local file path. This method requires manual updates if the library version changes and manual switching between debug and release versions.
Adding jQuery to an empty ASP.NET web project using the ScriptManager control. This control helps manage script references, automatically switching between debug and release versions based on the <compilation debug=”true”/> setting in web.config. It can also be configured to load jQuery from a CDN if the EnableCdn property is set to true. The ScriptManager uses a ScriptResourceDefinition object, typically defined in the Global.asax file, to map a script name (like “jquery”) to its local and CDN paths for debug and release modes. It also includes a fallback mechanism to load the local copy if the CDN is unavailable.
Adding jQuery to an ASP.NET Master Page ensures that all content pages using that Master Page automatically include the library. This can be done by adding the <script> block or ScriptManager control to the Master Page.
Adding jQuery programmatically to a web form using the Page.ClientScript.RegisterClientScriptInclude method in the code-behind file. This method adds the script block within the <form> element.
In the default ASP.NET Web Application templates, jQuery is often included using the ScriptManager control in the Master Page, leveraging the Microsoft CDN by default, with mapping defined by the AspNet.ScriptManager.jQuery package. This mapping can be changed to use a different CDN, such as Google CDN, by updating the ScriptResourceMapping in the BundleConfig class.
In ASP.NET MVC applications, jQuery can be included using the <script> tag in views. A common method is using bundling, which combines multiple script files into a single file to reduce HTTP requests. Bundling is configured in the BundleConfig class using ScriptBundle. Bundling can also be configured to load jQuery from a CDN by setting the UseCdn property and providing the CDN path. A fallback mechanism should be included in the view to load the local file if the CDN fails.
Once jQuery is included, you can write client-side code to interact with your web page. A common starting point is using the $(document).ready() function, which executes code when the Document Object Model (DOM) is fully loaded.
jQuery provides powerful features for manipulating elements on a web page:
Selectors: These are jQuery constructs used to retrieve elements based on specified conditions. They can return single or multiple elements. Since ASP.NET controls are rendered as HTML elements, they can be selected using standard jQuery selectors. Types of selectors include Basic selectors (by tag, class, ID, or combination), Hierarchy selectors (selecting based on relationships like parent/child), Attribute selectors (selecting based on element attributes), Form selectors (working with form elements), and Position filters (selecting elements based on their position in a collection). Examples of selectors used in the sources include #identifier for selecting by ID, .class for selecting by CSS class, html_tag for selecting by HTML tag, [attribute*=”value”] for selecting by attribute containing a value, :first, :last, :odd, :even, :eq(i), :lt(i), :gt(i) for position filtering. The $(this) object refers to the current jQuery object in a chain or callback.
DOM Traversal: jQuery provides methods to navigate the DOM tree, such as accessing parent (.parent(), .parents()), child (.children(), .find()), and sibling (.siblings()) elements.
DOM Manipulation: Elements can be added (.append(), .prepend(), .appendTo()), removed (.remove()), or cloned (.clone()) at runtime using client code. Methods like .addClass() and .removeClass() are used to manage CSS classes.
Visual Effects and Animations: jQuery simplifies adding visual effects. Built-in methods include .show(), .hide(), .toggle() for displaying elements; .fadeIn(), .fadeOut(), .fadeTo(), .fadeToggle() for fading; and .slideUp(), .slideDown(), .slideToggle() for sliding effects. Custom animations can be created with .animate() by changing numeric CSS properties over time. Animations can be stopped using .stop() or .finish(). The duration of animations can be specified in milliseconds or using keywords like “slow” and “fast”. Specific applications of effects mentioned include animating Menu controls, creating digital clocks, animating AdRotator alt text, animating images in TreeView nodes, creating scrolling text, building vertical accordion menus, and showing/hiding GridView controls. The jQuery UI library provides additional effects like “explode” and enhanced easing methods like “easeOutBounce”.
Event Handling: Events occur when a user interacts with the page or during page milestones. An event handler is a function executed when an event occurs. jQuery 1.7+ recommends the .on() method for binding event handlers. It can attach single events, multiple events to one handler, or different events to different handlers. Event delegation is a technique where a single event handler is attached to a parent element to manage events for its children, including future children. This is possible due to event bubbling, where events in a child element travel up the DOM tree. Event bubbling can be stopped using .stopPropagation(). The .one() method attaches an event handler that executes at most once. Events can be triggered programmatically using .trigger(). Data can be passed with events, typically as a JSON string. Events can also use namespacing (e.g., click.myNamespace) to group handlers. Event handlers can be removed using .off(). Examples of events discussed include mouse events (mouseover, mouseout, click, dblclick, mousemove), keyboard events (keyup), and form events (focus, blur, change).
Working with Graphics: jQuery aids in integrating graphics by providing utilities for effects, animations, and event handlers on elements like <img>, ImageButton, and ImageMap. Examples include creating spotlight effects on images, zooming images on mouseover, building image scrollers, creating photo galleries (using z-index or ImageMap), using images in Menu controls, creating a 5-star rating control (as a User Control), and previewing image uploads in MVC. The File API (window.File, window.FileReader) and its onloadend event are used for previewing image uploads.
Ajax (Asynchronous JavaScript and XML): Ajax allows communication with the server without full page refreshes, updating parts of the page transparently. jQuery simplifies Ajax with methods like the generic .ajax() for various request types (GET, POST, etc.). Global default settings can be configured with .ajaxSetup(). Shortcut methods like .load() (for text/HTML content) and .getJSON() (for JSON data via GET) are also available. jQuery Ajax can be used to consume various server-side endpoints in ASP.NET, including page methods (static/shared methods marked with [WebMethod]), Web services (ASMX), WCF services (Ajax-enabled SVC), Web API (HTTP API), and generic HTTP handlers (ASHX). The $.getJSON() method is particularly useful for retrieving JSON data from endpoints like Web APIs. For WCF services and page methods expecting JSON input, contentType: “application/json; charset=utf-8” and data as a JSON string are used. Accessing returned data from Web Services, WCF Services, and Page Methods often involves accessing a .d property of the response object.
Plugins: jQuery’s plugin architecture allows extending the core library. Plugins are JavaScript files included alongside jQuery. They typically provide configurable functionalities. New plugins are published to the NPM (Node Package Manager) repository. Creating a plugin involves defining methods in the jQuery namespace (for utility functions like $.sampleMethod()) or on jQuery.fn (alias for jQuery.prototype, for methods callable on DOM elements like $(“#element”).myMethod()). Using a wrapping function (function($){…})(jQuery) allows using the $ alias safely within the plugin, even if $.noConflict() has been called elsewhere. Plugin methods often use .each() to ensure they operate correctly on collections of matched elements. Good practices for plugins include providing default options using $.extend() to allow customization and returning the this object (the jQuery object) to enable method chaining. Plugins can also define different actions or functionalities based on arguments passed to the method. The jQuery validation plugin is a popular example available from http://jqueryvalidation.org and downloadable via package managers like NuGet or Bower (which requires Node.js, NPM, and Git). This plugin provides methods like .validate() to validate forms based on defined rules and messages, and .resetForm() to clear validations. It offers features like custom error message placement and handling invalid forms.
This book aims to impart the skill of learning jQuery and using it in ASP.NET applications by exploring diverse recipes for common problems in ASP.NET 4.6 applications. The examples are based on Visual Studio 2015 and jQuery 2.1.4 and were tested in Internet Explorer 11.0.96, Mozilla Firefox 38.0.1, and Google Chrome 47.0.2526. Familiarity with Visual Studio and MS SQL Server is preferred but not mandatory for the reader.
jQuery and ASP.NET Development Guide
Based on the sources you provided, ASP.NET is a framework used for creating web applications. The book specifically focuses on writing client script using jQuery in ASP.NET 4.6 applications. Sonal Aneel Allana, the author, has experience teaching in areas including .NET and ASP.NET.
The sources describe how to integrate and use the jQuery library within ASP.NET Web Forms and MVC applications. The book covers various aspects of using jQuery with ASP.NET, including:
Getting Started with downloading and including jQuery in ASP.NET 4.6 Web and MVC projects. This involves understanding CDNs, using NuGet Package Manager, adding jQuery via script blocks, using the ScriptManager control, adding it to ASP.NET Master Pages, and adding it programmatically to web forms. The default Web Application template in ASP.NET also includes a reference to jQuery, typically using the ScriptManager control.
Using jQuery Selectors with ASP.NET Controls. When an ASP.NET page is viewed in a browser, controls are rendered as HTML elements, making them selectable with standard jQuery selectors. The book demonstrates selecting controls by ID, CSS class, HTML tag, attribute, or position in the DOM. Selectors can also be used in ASP.NET MVC applications.
Event Handling Using jQuery in ASP.NET. This includes responding to mouse, keyboard, and form events, as well as using event delegation and detaching events.
DOM Traversal and Manipulation in ASP.NET. Techniques covered include accessing parent, child, or sibling elements, refining selection using filters, and adding or removing elements at runtime.
Visual Effects in ASP.NET Sites. Recipes discuss creating animation effects on various ASP.NET controls like Panel, AdRotator, TreeView, Menu, and GridView.
Working with Graphics in ASP.NET Sites and MVC. This involves applying effects like zooming and scrolling to images and building components like image galleries, image previews, and rating controls using jQuery. ASP.NET server controls such as Image, ImageButton, and ImageMap, as well as plain HTML image elements in MVC, can be manipulated.
Ajax Using jQuery in ASP.NET. The book explains how to make Ajax calls to interact with server-side components such as page methods, Web services (.asmx), WCF services (.svc), Web API, MVC controllers, and HTTP handlers (.ashx).
To work with the examples discussed, requirements include Visual Studio 2015, MS SQL Server 2014, the Northwind database, the jQuery library, the jQuery UI library, a web browser, NPM, and Bower. The book is aimed at ASP.NET developers who want to use jQuery to write client scripts for cross-browser compatibility. While familiarity with Visual Studio and MS SQL Server is preferred, it is not compulsory.
Mastering jQuery Selectors in ASP.NET
Based on the sources, jQuery selectors are fundamental constructs used to retrieve elements on a web page based on a specified condition. They provide a mechanism to access web page elements when writing client scripts, which is essential for manipulating these elements. While standard JavaScript allows accessing elements by their unique IDs using methods like document.getElementById(), selectors offer more flexibility, enabling developers to select elements based on attributes other than ID, or to retrieve and manipulate multiple elements simultaneously.
Selectors are particularly relevant in the context of ASP.NET development because when an ASP.NET page is viewed in a browser, the server controls are rendered as HTML elements. This conversion means that standard jQuery selectors can be applied to manipulate these rendered ASP.NET controls just like any other HTML element. The sources provide a table illustrating the mapping of common ASP.NET controls to their rendered HTML elements and tags, such as GridView rendering as <table>, Button as <input type=”submit”/>, and Label as <span>. Selectors are also usable in ASP.NET MVC applications as they typically use raw HTML markups or HTML helper methods to render content.
The sources classify jQuery selectors into several broad types:
Basic selectors: These are similar to CSS selectors and are used to retrieve elements based on their HTML tag, CSS class, element ID, or a combination. Examples include selecting all elements ($(“*”)), all <div> elements ($(“div”)), all elements with a specific CSS class ($(“.highlight”)), an element with a specific ID ($(“#footer”)), or a combination.
Hierarchy selectors: Also resembling CSS selectors, these are used to select child or descendant elements within the structure of the Document Object Model (DOM) tree. Examples include selecting all <p> elements inside <div>s ($(“div p”)) or immediate children <p> of <div>s ($(“div > p”)).
Attribute selectors: These selectors retrieve elements based on the attributes they possess. Examples include selecting all <a> elements with an href attribute ($(“a[href]”)), or those whose href attribute contains ($(“*=”)), starts with ($(“^=”)), or ends with ($(“$=”) a specific string.
Form selectors: Specifically designed to work with various form elements like inputs, checkboxes, and radio buttons. Examples include selecting elements by type ($(“:button”), “:checkbox”, “:radio”), all form elements ($(“:input”)), or elements based on state (“:checked”, “:selected”, “:enabled”, “:disabled”).
Position filters: These selectors retrieve elements based on their position within a collection, often relative to siblings. Examples include selecting the first element in a collection (:first), the last (:last), those at an odd or even index (:odd, :even), at a specific index (:eq(i)), or with an index less than (:lt(i)) or greater than (:gt(i)) a certain value.
Anonymous functions are frequently used in conjunction with selectors, often passed as arguments to other functions that operate on the selected elements.
The sources provide several recipes demonstrating the practical application of these selectors within ASP.NET applications:
Using the ID selector (#identifier) to access controls like TextBox, RadioButtonList, DropDownList, CheckBoxList, CheckBox, and Button in a web form. This often involves using the ASP.NET ClientID property to get the rendered HTML ID.
Employing the CSS class selector (.class) to work with controls like Image, Panel, and BulletedList.
Selecting controls like GridView by their rendered HTML tag ($(“html_tag”)), often combined with attribute filters or hierarchy selectors to target specific parts like rows (<tr>) or cells (<td>).
Accessing controls like Hyperlink based on their attributes, such as the href attribute rendered from the NavigateUrl property.
Selecting list items (<option> rendered from ListItem in ListBox or DropDownList) or other elements based on their position within the DOM, using position filters like :first-child, :last-child, :lt(), :gt(), and :nth-child.
Using selectors to dynamically enable or disable controls on a web form.
Demonstrating the use of various selectors within ASP.NET MVC applications.
Based on the sources, event handling is a fundamental concept in client scripting using jQuery in ASP.NET applications.
An event is defined as an action that occurs when the user interacts with the web page or when certain milestones are completed, such as a page loading in the browser. Examples include moving the mouse, pressing a key, clicking a button or link, keying in text in a field, or submitting a form. Events can be user- or system-initiated.
An event handler is a function that is executed when a specific event occurs. Writing or binding an event handler for a particular event allows developers to program the desired actions in response to user or system interactions. jQuery eases client scripting tasks, including event handling, adding to the interactive experience for the end user.
When working with events, event delegation is an important mechanism. It allows you to attach a single event handler to a parent element instead of attaching individual event handlers to each child element. This approach optimizes the number of event handlers on the page. Event delegation is also useful for wiring events to child elements that do not exist when the page initially loads but are added later at runtime.
Event delegation is made possible because of event bubbling. Event bubbling is the process where an event occurring in a child element travels up the Document Object Model (DOM) tree to its parent, then to its parent’s parent, and so on, until it reaches the root element (the window). For example, a click event on a table cell (<td>) bubbles up through the table row (<tr>), the table (<table>), and eventually to the <body>, <html>, and window elements. The parent element can intercept the event as it bubbles up, allowing a single handler on the parent to manage events for its descendants. jQuery provides a .stopPropagation() method to prevent an event from bubbling further up the DOM tree.
jQuery offers several methods for binding events. Prior to jQuery 1.7+, methods like .bind(), .live(), and .delegate() were used. However, these are now deprecated, and the .on() method is recommended for event binding in jQuery 1.7+.
The .on() method can be used in various ways:
Attaching a single event to a handler: For example, $(“#btnTest”).on(“click”, function(){…});.
Attaching multiple events to a handler: The same handler can respond to multiple events listed with spaces, like $(“#imgTest”).on(“mouseover mouseout”, function(){…});.
Attaching different events to different handlers: An object can be passed mapping event names to handler functions, for example, $(“#imgTest”).on({ mouseover: function(){…}, mouseout: function(){…} });.
Event delegation: By specifying a selector as a second argument, the handler is attached to the parent element but only executed for descendant elements matching the selector. For example, $(“#tblTest”).on(“click”, “tr”, function(){…}); attaches the click handler to the table, but it only runs when a table row (<tr>) inside the table is clicked. This is demonstrated in a recipe to attach events to dynamically added rows.
Passing data to events: Data can be passed as a JSON string or other data types when binding the event, which can then be accessed in the event handler. This is demonstrated in a recipe using the .trigger() method.
Specific types of events discussed in the sources include:
Mouse events: Such as mouseover (when the mouse pointer enters an element) and mouseout (when it leaves an element). The .hover() method is a shortcut for binding mouseover and mouseout handlers. A recipe demonstrates handling these events to display a custom tooltip for text boxes.
Keyboard events: Such as keyup (when a key is released). Other keyboard events mentioned are keydown and keypress. A recipe uses the keyup event to create a character count for a text area.
Form events: Such as focus (when an element receives focus) and blur (when an element loses focus). A recipe uses these events to apply styles and display background text or validation errors on form controls.
In the context of ASP.NET, when a page is viewed in the browser, server controls are rendered as HTML elements. This means that standard jQuery event handling techniques, including the use of selectors and the .on() method, can be applied to these rendered HTML elements corresponding to ASP.NET controls.
To ensure an event handler is executed at most once, the .one() method can be used. Once the event is triggered and the handler is executed, the handler is automatically detached from the element. This is shown in a recipe for a “See More…” link that should only work once.
jQuery’s .trigger() method allows events to be invoked programmatically. This means client-side code can simulate user actions or system events. A recipe demonstrates using .trigger() to simulate a click on an “Edit” link in a GridView row when the user double-clicks the row itself.
Events can also have event data passed along with them and can utilize event namespacing. Namespacing allows multiple handlers to be attached to the same event type for the same element without interfering with each other; handlers can then be triggered or detached based on their namespace. A recipe illustrates passing data as a JSON object and using namespacing (click.radioclick1, click.radioclick2) to trigger different alert or confirm boxes based on which radio button was clicked.
Finally, the .off() method is used to detach event handlers from elements. It can remove specific handlers, all handlers for a particular event type, or all handlers (including namespaced ones) depending on how it is used. A recipe shows how to use .off() to remove focus and blur event handlers from text boxes when a checkbox is unchecked.
DOM Traversal and Manipulation with jQuery
Based on the sources, DOM manipulation is a key concept when working with client scripts like jQuery in ASP.NET applications.
The Document Object Model (DOM) is presented as a representation of web pages in a structured, tree-like format. Each part of the web page is a node in this tree, and these nodes have properties, methods, and event handlers. The web page itself is the document object, accessible via window.document. HTML elements on the page become element nodes, such as <head> or <body>, which can have children nodes like <table>, <div>, or <input>. The DOM is described as an object-oriented model that is language-independent, offering a common Application Programming Interface (API) that allows programming languages like JavaScript to manipulate the style, structure, and content of web pages.
jQuery provides many methods for interacting with the DOM, including manipulating elements.
One specific aspect of DOM manipulation discussed is adding and removing DOM elements. jQuery offers methods to perform these actions at runtime using client code.
The sources illustrate adding DOM elements using the .clone() method. This method creates a deep copy of the matched elements, including their descendants and text nodes. When cloning elements, it’s necessary to update properties like ID, name, and value of the cloned elements and their children to avoid duplicates. The cloned elements can then be added to the DOM using methods like .appendTo(), which inserts the elements at the end of a target element. A recipe demonstrates cloning a Panel control (addPanel CSS class) and its contents, updating the IDs and names of the cloned elements, and appending them to a container div.
For removing DOM elements, the jQuery method .remove() is used. This method not only removes the matched elements but also their descendants, and it removes all related data and events associated with them. A recipe shows how to remove a dynamically added Panel control using its ID and the .remove() method after user confirmation.
The sources also touch upon other manipulation strategies, such as adding items to controls at runtime. This involves using methods like .prepend() to insert content at the beginning of a matched element or .append() to insert content at the end. The $.map() function can be used to transform data (like an array of strings) into an array of DOM elements (<option> or <li>) before appending/prepending them. This is demonstrated in a recipe for adding items to ListBox, DropDownList, and BulletedList controls dynamically.
While focusing on manipulation, the sources also reference DOM traversal as a related concept. Traversal methods allow accessing elements in the DOM tree, such as parent, child, or sibling elements. Examples of traversal methods mentioned or used in the context of accessing controls (though not explicitly manipulation methods) include .parent() to get the immediate parent, .children() for immediate descendants, .find() for descendants matching a filter, .siblings() for elements on the same level, .next() for the immediate sibling, and filtering selections using methods like .filter(). These traversal methods are often used before performing manipulation on the selected elements.
Chapter 4 of the source material is specifically dedicated to “DOM Traversal and Manipulation in ASP.NET”, covering recipes on adding/removing elements, accessing parent/child controls, accessing sibling controls, refining selection using filters, and adding items to controls at runtime.
Affiliate Disclosure: This blog may contain affiliate links, which means I may earn a small commission if you click on the link and make a purchase. This comes at no additional cost to you. I only recommend products or services that I believe will add value to my readers. Your support helps keep this blog running and allows me to continue providing you with quality content. Thank you for your support!
The provided texts offer a comprehensive exploration of object-oriented programming (OOP) in JavaScript, starting with fundamental concepts like objects, object literals, factory functions, and constructor functions, contrasting them with procedural programming. The material progresses to cover prototypal inheritance, explaining the prototype chain, constructor properties, and the significance of shared methods for memory efficiency and code reuse. Advanced topics such as property descriptors, abstraction, and the use of Getters and Setters are discussed to illustrate how to manage object behavior and encapsulate data. The explanation extends to modern JavaScript features including ES6 classes as syntactic sugar over prototypes, hoisting behavior, and the creation of static methods and private members. Furthermore, the texts introduce modules (CommonJS and ES6) for organizing and reusing code, along with the role of npm for package management and third-party libraries. Finally, the sources touch upon asynchronous JavaScript, covering callbacks, Promises, and async/await for handling non-blocking operations.
Node.js and JavaScript Fundamentals Study Guide
Quiz
Explain the primary purpose of both Node.js and Visual Studio Code as introduced in the source material. Why are both recommended for the course?
Describe the process of creating a new JavaScript file and running it using Node.js within the Visual Studio Code environment. Include the specific commands or shortcuts mentioned.
What are the key components of the Visual Studio Code interface, as highlighted in the text? Briefly explain the function of the activity bar and the status bar.
Explain the difference between primitive and object data types in JavaScript, focusing on how they are passed (by value vs. by reference) and the implications of this difference.
Define what it means for objects in JavaScript to be dynamic. Provide an example of how you can dynamically add, modify, and delete properties from an existing object.
What is a JavaScript closure? Explain how closures enable the creation of private variables and methods within constructor functions.
Describe the purpose and basic syntax of Getters and Setters in JavaScript. How do they contribute to encapsulation within object-oriented programming?
Explain the concept of the prototype chain in JavaScript. How does it enable objects to inherit properties and methods from other objects?
What is the significance of the this keyword in JavaScript, and how does its behavior differ when a method is detached from its object context? How does strict mode affect this?
Briefly explain the concept of abstraction in object-oriented programming and describe at least two ways to achieve private properties or methods in JavaScript classes as discussed in the source material.
Quiz Answer Key
Node.js is a runtime environment that allows JavaScript code to be executed outside of a web browser, primarily used for backend development. Visual Studio Code (VS Code) is an Integrated Development Environment (IDE) used for writing and debugging code. Both are recommended for the course to provide an environment for writing and executing JavaScript code for backend applications.
To create a new JavaScript file in VS Code, open the project folder and click the new file icon or use the keyboard shortcut (Ctrl+N or Cmd+N). Name the file with a .js extension (e.g., code.js). To run it with Node.js, open the integrated terminal in VS Code (Ctrl+` or Cmd+`) and use the command node filename.js (e.g., node code.js).
Key components of VS Code include the activity bar (on the left with icons for Explorer, Search, Source Control, Run and Debug, and Extensions) and the status bar (at the bottom showing errors/warnings, line number, and language). The activity bar allows navigation between project files, search, version control, debugging, and extensions. The status bar provides contextual information about the current file and project.
Primitive data types (number, string, boolean, etc.) are passed by value, meaning a copy of the value is assigned to a new variable, and changes to one do not affect the other. Object data types (including objects, arrays, and functions) are passed by reference, meaning both variables point to the same object in memory, so changes to one are reflected in the other.
Objects in JavaScript are dynamic because you can add, modify, and delete their properties and methods after they have been created. For example, if you have const person = { name: ‘Alice’ };, you can add a property with person.age = 30;, modify it with person.name = ‘Bob’;, and delete it with delete person.age;.
A JavaScript closure is an inner function that has access to variables in its outer (enclosing) function’s scope, even after the outer function has finished executing. Closures enable the creation of private variables by defining variables within the outer function’s scope, which are then only accessible by the inner function’s methods, effectively hiding them from the outside.
Getters are methods that allow you to retrieve the value of an object’s property, while Setters allow you to modify the value of a property. They are defined within an object literal or class using the get and set keywords followed by the property name and a function. They contribute to encapsulation by providing controlled access to an object’s internal properties, allowing for validation or other logic during property access or modification.
The prototype chain in JavaScript is a mechanism of inheritance where objects can inherit properties and methods from other objects. Every object (except the root object) has an internal link to another object called its prototype. When you try to access a property of an object, JavaScript first looks at the object itself. If the property is not found, it then looks at the object’s prototype, and so on, up the chain until the property is found or the end of the chain is reached.
The this keyword in JavaScript refers to the object that is currently executing the code. Its behavior depends on how a function is called. When a method is detached from its object (e.g., assigned to a variable and called independently), this typically loses its binding to the original object and may refer to the global object (in non-strict mode in browsers) or be undefined (in strict mode). Strict mode enforces more consistent behavior and helps prevent unintended global variable modifications.
Abstraction in OOP involves hiding complex implementation details and exposing only the essential information to the user. Two ways to achieve private properties or methods in JavaScript classes discussed are using ES6 Symbols (which create unique, less accessible identifiers, though not truly private) and using ES2022 private class fields and methods denoted by a hash (#) prefix, which provides truly private encapsulation not accessible from outside the class.
Essay Format Questions
Discuss the significance of modularity in JavaScript development, particularly within the Node.js environment. Explain how CommonJS and ES6 modules facilitate encapsulation and code organization, highlighting their key differences and use cases based on the source material.
Analyze the concept of asynchronous programming in JavaScript. Compare and contrast the use of callbacks, promises, and async/await for managing asynchronous operations, discussing the benefits and drawbacks of each approach as presented in the provided excerpts.
Explain the principles of object-oriented programming (OOP) as introduced in the source material. Discuss how JavaScript supports these principles through features like constructor functions, prototypes, classes, and encapsulation techniques such as closures and Getters/Setters.
Describe the role and importance of package management in Node.js using npm. Discuss how package.json and semantic versioning contribute to dependency management, project stability, and collaboration among developers, referencing the concepts of global vs. local package installations.
Discuss the concept of privacy and data encapsulation in JavaScript. Analyze the different techniques for achieving privacy, such as naming conventions, closures, Symbols, weak maps, and private class fields (#), evaluating their effectiveness and use cases based on the information provided in the source material.
Glossary of Key Terms
Node.js: A runtime environment that allows JavaScript code to be executed outside of a web browser, primarily used for server-side development.
Visual Studio Code (VS Code): A free source code editor made by Microsoft for Windows, Linux, and macOS, used for writing and debugging code.
IDE (Integrated Development Environment): A software application that provides comprehensive facilities to computer programmers for software development.
JavaScript: A high-level, often just-in-time compiled, and multi-paradigm programming language that conforms to the ECMAScript specification.
Console: A window in which text-based output from and input to a computer program takes place. In web development and Node.js, often used for logging information.
File Explorer (Windows): A file manager application used by Windows operating systems for browsing and managing files and folders.
Finder (macOS): The default file manager and the graphical user interface shell used in all Macintosh operating systems.
Project: A collection of related files and folders that constitute a software development effort.
File Extension: A suffix at the end of a filename indicating the type of file. For JavaScript files, it is .js.
console.log(): A JavaScript function used to print output to the console.
Integrated Terminal: A terminal emulator directly within an IDE like VS Code, allowing developers to run command-line tools without switching applications.
Activity Bar (VS Code): The vertical bar on the left side of the VS Code window that allows switching between different views like Explorer, Search, etc.
Status Bar (VS Code): The horizontal bar at the bottom of the VS Code window that displays information about the current project and file.
Primitive Data Types: Basic data types in JavaScript that are passed by value, including number, string, boolean, big int, undefined, null, and symbol.
Object Data Type: A complex data type in JavaScript that can hold collections of key-value pairs. Includes objects, arrays, and functions, and is passed by reference.
Pass by Value: When a variable holding a primitive value is assigned to another variable, a copy of the value is created in a new memory location.
Pass by Reference: When a variable holding a reference to an object is assigned to another variable, both variables point to the same object in memory.
Dynamic Objects: Objects in JavaScript that can have their properties and methods added, modified, or deleted after creation.
Constructor Function: A function in JavaScript that is used with the new keyword to create and initialize objects.
Instantiation: The process of creating a new instance of an object from a class or constructor function.
Closure: An inner function in JavaScript that has access to the outer (enclosing) function’s variables—scope chain—even after the outer function has finished executing.
Encapsulation: The bundling of data (properties) and methods that operate on the data into a single unit (object), and restricting direct access to some of the object’s components.
Getter: A special method that is used to get the value of an object’s property.
Setter: A special method that is used to set the value of an object’s property.
Object Literal: A way to create objects in JavaScript using curly braces {} and defining properties as key-value pairs.
Prototype: An object that serves as a template for other objects. Objects inherit properties and methods from their prototype.
Prototype Chain: A sequence of objects linked together via their prototypes, used for inheritance and looking up properties and methods.
this Keyword: A keyword in JavaScript that refers to the object that is currently executing the code. Its value depends on how the function is called.
Strict Mode: A feature in JavaScript that enforces stricter parsing and error handling on your code, helping to avoid common pitfalls and unsafe practices.
Abstraction (OOP): Hiding complex implementation details and showing only essential information to the user.
ES6 (ECMAScript 2015): A major update to the JavaScript language standard that introduced new features like classes, modules, arrow functions, etc.
Symbol (ES6): A primitive data type whose instances are unique and immutable, often used to create private object properties.
Weak Map (ES6): A collection of key-value pairs in which keys must be objects, and unlike Maps, WeakMap keys are not strongly referenced, allowing them to be garbage collected if they are not referenced elsewhere.
Private Class Fields (ES2022): Class fields declared with a # prefix that are truly private and not accessible from outside the class.
Module: A self-contained unit of code that can be imported and used in other parts of a program. In Node.js, each file is treated as a separate module.
CommonJS: A module system for JavaScript, primarily used in Node.js, that uses require() to import modules and module.exports to export them.
ES6 Modules: A standardized module system for JavaScript that uses import to import modules and export to export them, supported in modern browsers and Node.js.
require(): A function in CommonJS used to import modules.
module.exports: An object in CommonJS used to define what a module exports.
import (ES6): A keyword in ES6 used to import modules.
export (ES6): A keyword in ES6 used to export modules.
package.json: A file at the root of a Node.js project that describes the project, its dependencies, scripts, and other metadata.
npm (Node Package Manager): The default package manager for Node.js. It is the world’s largest software registry, containing over a million packages.
Dependency: A library or package that a project relies on to function correctly.
npm install: A command used to download and install the dependencies listed in a project’s package.json file.
Semantic Versioning (SemVer): A versioning standard using a three-part number (MAJOR.MINOR.PATCH) to indicate the nature of changes in a software release.
Global Packages (npm): Packages installed in a system-wide directory, making them accessible from any project. Installed using the -g or –global flag.
Local Packages (npm): Packages installed within a specific project’s node_modules directory, only available to that project.
npm publish: A command used to upload a package to the npm registry.
Asynchronous Programming: A programming paradigm that allows multiple tasks to run concurrently without blocking the main execution thread.
Synchronous Programming: A programming paradigm where tasks are executed sequentially, and each task must complete before the next one can start.
Callback Function: A function passed as an argument to another function, to be executed at a later point, often after an asynchronous operation completes.
Callback Hell (Pyramid of Doom): A situation in asynchronous JavaScript code where multiple nested callbacks make the code difficult to read and maintain.
Promise: An object representing the eventual completion (either success or failure) of an asynchronous operation and its resulting value.
then(): A method of a Promise that is called when the promise is fulfilled (resolved).
catch(): A method of a Promise that is called when the promise is rejected.
async: A keyword used to define an asynchronous function, which implicitly returns a Promise.
await: A keyword used inside an async function to pause the execution of the function until a Promise is resolved or rejected.
try…catch: A statement used to handle exceptions (errors) in JavaScript code, including within async functions.
Briefing Document: Asynchronous JavaScript and Module Management
This document provides a detailed review of the main themes and important ideas presented in the provided source materials, focusing on asynchronous JavaScript, module management in Node.js, and object-oriented programming concepts.
Part 1: Introduction to Node.js and Development Setup
Main Themes: Setting up a development environment with Node.js and Visual Studio Code (VS Code), basic JavaScript syntax, and an introduction to Object-Oriented Programming (OOP).
Key Ideas and Facts:
Node.js Installation: The document guides users through downloading and installing Node.js, recommending the default settings for most users.
“node.js once downloaded open the installer and follow the onscreen instructions the default settings are suitable for most users so you can proceed with them unless you have specific preferences”
VS Code Installation and Basic Usage: It provides instructions for downloading and installing VS Code, emphasizing that default settings are sufficient. Basic operations like creating a new project folder, adding files (.js extension is crucial), writing and saving code (Ctrl/Cmd + S), and executing JavaScript using the integrated terminal (node filename.js) are covered.
“the name of this file doesn’t matter but the file extension does”
“to save it I can do command s or on Windows it would be control s”
“I’ll type node and then the name of our file which is code. JS”
VS Code Interface Overview: The document introduces key components of the VS Code interface, including the activity bar (folder, search, source control, run and debug, extensions), status bar (errors/warnings, line number, language), command palette (Ctrl/Cmd + Shift + P), and basic customization options (color theme, text size).
“on the left hand side is the activity bar where we see a list of icons”
“on the bottom of the screen is the status bar here in Blue”
“you can access the command pallet by going to view and then command pallet now another way to do that is with the keyboard shortcut of command shift and P”
Recommended VS Code Extensions: Two extensions are recommended for the course: Live Server (for hot reloading in web development) and Quokka.js (for inline JavaScript output).
“for this course there are two vs code extensions that I suggest and that we will be using throughout this course so click on the icon for extensions and type in Live server then you can install this extension”
“another extension that we’ll be using for the early part of this course is quoka you type in quoka so select this one and then install it”
Introduction to OOP: The document introduces the fundamental concept of Object-Oriented Programming as a paradigm focused on organizing software design around “data or objects rather than focusing solely on functions and logic.” Objects are described as instances of classes, which serve as blueprints.
“objectoriented programming or o op is a programming Paradigm built around the concept of objects at its core oop organizes software design around data or objects rather than focusing solely on functions and logic objects are instances of classes which serve as blueprints for creating and managing data and”
Part 2: JavaScript Fundamentals and Object-Oriented Concepts
Main Themes: Data types, pass by value vs. pass by reference, dynamic nature of objects, loops, object literals, factory functions, constructor functions, the this keyword, prototypes, classes, static methods, abstraction, encapsulation, Getters and Setters, and property attributes.
Key Ideas and Facts:
Data Types: JavaScript supports eight data types: seven primitive (number, string, boolean, bigint, undefined, null, symbol) and one complex (object, including arrays and functions).
“JavaScript supports eight different data types which include seven primitive types and one complex type”
Pass by Value vs. Pass by Reference: Primitive types are passed by value (copied), so changes to one variable do not affect others. Reference types (objects, arrays, functions) are passed by reference (point to the same memory location), so changes in one variable are reflected in others.
“primitive types these are passed by value so when you work with primitive values these are passed by copy”
“reference types like objects are handled differently so they are passed by reference meaning both variables point to the same object in memory”
Dynamic Objects: JavaScript objects are dynamic, allowing properties and methods to be added, modified, or deleted after creation. Using const with an object prevents reassignment of the variable but not modification of the object’s contents.
“objects in JavaScript are inherently Dynamic which means that you can add or modify their properties and Methods at any time after their creation”
“using the cons keyword with an object declaration ensures that the variable cannot be reassigned to a different value however the contents of the object it points to such as its properties and methods can still be altered or extended”
Loops: The for…of loop is introduced as ideal for iterating over array elements.
“for arrays we can use the four of loop so the four of loop is ideal for ating over array elements”
Object Literals, Factory Functions, and Constructor Functions: The document explains different ways to create objects in JavaScript, including simple object literals, factory functions (returning objects), and constructor functions (using new and the this keyword).
The this Keyword: The behavior of this depends on how a function is called. In constructor functions, this refers to the newly created object. Detaching a method from its object can cause this to lose its original context (referring to the global object or undefined in strict mode).
“the this keyword in JavaScript behaves differently based on how a function is called This Behavior can lead to unexpected results especially when functions are detached from the object context”
Prototypes: Every object in JavaScript has a prototype (except the root object), which it inherits properties and methods from. Constructor functions have a prototype property that defines the prototype for all instances created with that constructor, optimizing memory usage by sharing methods.
“in JavaScript every object has a prototype except for the root object which is at the top of the Prototype chain the Prototype acts as a template or parent from which the object inherits methods and properties”
“Constructor functions have their own prototype in JavaScript functions are objects so they have their own prototype property which is used to assign properties and methods to instances created by the Constructor function”
Classes (ES6): ES6 introduced class syntax, which provides a more structured way to create objects and handle inheritance, implicitly using strict mode.
“if we were to to use classes they implicitly use strict mode to avoid these issues instead of using a Constructor function I’ll specify it to be a class”
Static Methods: Static methods are associated with the class itself, not instances of the class, and are called directly on the class.
“static methods are defined directly on the class itself and are called on the class rather than on an instance of the class”
Abstraction: Abstraction involves hiding complex implementation details and exposing only necessary parts through a public interface (e.g., public methods interacting with private methods). Private methods can be simulated using naming conventions (underscore prefix), Symbols (pseudo-private), or truly private class fields (using # prefix in ES2022+).
“abstraction and programming involves hiding complex implementation details and exposing only the necessary parts of an object this is commonly achieved through private properties and methods”
Encapsulation: Encapsulation is the bundling of data (properties) and methods that operate on the data, restricting direct access to some of the object’s components. This is achieved through private properties and methods, controlled access via Getters and Setters, and module scope.
Getters and Setters: Getters (get) and setters (set) are special methods used to control how object properties are accessed and modified, allowing for validation and encapsulation. Object.defineProperty (and Object.defineProperties) can be used to define these.
“Getters and sets are special methods that provide you with a way to get and set the properties of an object this encapsulation technique allows you to control how important values are accessed and modified in your objects it’s often used to ensure that data encapsulation and validation rules are followed”
Property Attributes (Descriptors): Properties have attributes (configurable, enumerable, writable) that determine if they can be deleted, iterated over, or modified. Object.defineProperty can be used to configure these attributes.
“configurable enumerable and writable for properties in our own objects”
“what are the property descriptors or attributes in JavaScript that determine whether a property can be accessed modified or iterated over in JavaScript property descriptors or attributes that determine whether a property can be accessed modified or iterated over are innumerable writable and configurable”
Closures: Closures are inner functions that have access to variables in their outer (enclosing) function’s scope, even after the outer function has finished executing. They are used to achieve encapsulation and create private variables.
“a closure means that inner function has access to variables declared in its outer function”
“closures are inner functions that are able to access variables defined in its outer function so in other words closure functions can access variables from their outer scope even after the outer function has finished executing now you would utilize closures in order to achieve encapsulation and to hide private variables or private properties”
WeakMap for Private Properties: WeakMap can be used to store private data in objects. Keys in a WeakMap are objects, and if an object key is garbage collected, its entry in the WeakMap is also removed, preventing memory leaks.
“weak Map is another way to implement private properties and methods in JavaScript classes”
“using weakmap for storing private data ensures that these details are not accessible from outside the class this is much more secure than using properties prefixed with an underscore”
Part 3: Module Management in Node.js
Main Themes: Understanding and using the Node.js module system (CommonJS and ES6 modules) for organizing and reusing code, global objects, and package management with npm.
Key Ideas and Facts:
Node.js as a Runtime Environment: Node.js allows JavaScript to run outside a web browser, primarily used for backend development (APIs, server-side applications). It uses an event-driven, non-blocking architecture.
“node.js is an open- Source cross-platform runtime environment that enables the execution of JavaScript outside of a web browser it’s primarily used for building servers set applications and networking tools”
Node.js Architecture and Features: Key features include its suitability for scalable, data-intensive, and real-time applications, quick startup and agility, real-world usage by major companies, the ability to use JavaScript for both frontend and backend, and a rich ecosystem (npm).
Runtime Environments: A runtime environment provides libraries and manages program execution. Web browsers have their own JavaScript engines (V8 in Chrome/Node.js, SpiderMonkey in Firefox, Chakra in Edge).
Node.js Module System (CommonJS): Each file in Node.js is treated as a separate module. require() is used to import modules, and module.exports (or exports) is used to export module contents.
“in node.js each file is treated as a separate module node.js provides a simple and efficient way to create modules and expose them to other parts of your application”
“node.js uses exports and module. exports to make functions and objects available to other files”
“we use the require function to include the module in another file”
Module Encapsulation (CommonJS): Modules in Node.js have their own scope, preventing global namespace pollution. Only explicitly exported items are accessible outside the module.
“one of the key benefits of using modules in nodejs is encapsulation by scope isolation each module has its own scope meaning its variables and functions are not accessible outside unless explicitly exported”
Exporting Defaults (CommonJS): module.exports = … is used to export a single default value (class, function, etc.).
“to export a class or function as the default export you use module. exports”
ES6 Modules: ES6 modules offer a more modern syntax for modularity in JavaScript (import and export).
“with es6 modules this provides a modern and cleaner syntax in order to achieve the same thing for JavaScript files that run in web browsers”
Global Objects in Node.js: Node.js provides built-in global objects (e.g., global, process, console, Buffer, timer functions) that are available in all modules. Custom global objects can be created by attaching properties to the global object.
“in nodejs Global objects are special objects that are available in all modules these objects provide essential functionality that could be access anywhere within a node.js application making them a fundamental part of the node.js runtime environment”
Loading Modules (require()): The require() function loads modules based on file paths. It’s best practice to use const when requiring modules to prevent accidental reassignment.
“nodejs uses the requir function to import modules which is a fundamental aspect of managing dependencies and modularity of your application”
“it’s a best practice to use the cons keyword as this prevents accidental reassignment of the module variable within your code”
Module Wrapping: Node.js wraps each module’s code in a function, providing scope isolation and access to module-specific variables (exports, require, module, __filename, __dirname).
“when node.js executes a module it does not run the code directly as written instead it wraps the module code inside a function this approach is not immediately apparent to the developer but it is fundamental to how nodejs operates”
OS Module: The built-in os module provides methods for retrieving system information (e.g., total memory, free memory).
“When developing applications that require system level data node.js provides a built-in module called OS which allows you to gather information about the underlying operating system”
FS (File System) Module: The built-in fs module allows interaction with the file system, providing synchronous (blocking) and asynchronous (non-blocking with callbacks or Promises) methods for file operations.
“node.js provides a powerful built-in module called FS for interacting with the file system this module is essential for reading from and writing to files on the server”
Package Management (npm): npm (Node Package Manager) is used to install, manage, and publish JavaScript packages. package.json file tracks project dependencies.
“npm which stands for node package manager which simplifies the addition of functionalities and accelerates the development process”
“npm is the default package manager for nodejs”
package.json: This file contains metadata about the project, including its name, version, dependencies, and scripts. npm init is used to create it.
“the package.json file is a central configuration file for your nodejs project it stores important metadata about your project such as its name version dependencies and scripts”
“you can initialize a new packagejson file by navigating to your project directory in the terminal and running the command mpm init”
Installing Packages (npm install): npm install <package-name> installs a package and adds it to node_modules and package.json (as a dependency). The –save-dev flag installs development dependencies.
“npm install <package-name> is the fundamental command used to install packages from the npm registry”
“to install a package as a development dependency which are tools needed for development and testing but not for running the application in production you can use the –save-dev flag”
node_modules: This directory stores all installed npm packages.
“npm installs these packages and their dependencies into a folder named nodeore modules in your project directory”
Version Control (Git and .gitignore): It’s crucial to exclude the node_modules directory from Git version control using a .gitignore file, as these dependencies can be restored using npm install.
“excluding known modules from Version Control is a best practice in nodejs development it keeps your project repository manageable speeds up operations like cloning and ensures that all developers are working with the same dependencies as defined in package.json”
Semantic Versioning (SemVer): Packages use semantic versioning (major.minor.patch) to indicate the type of changes in updates, helping developers understand the potential impact of updating dependencies. Carrots (^) and tildes (~) in package.json specify acceptable ranges for automatic updates.
“semantic versioning is a standard for versioning software which is widely adopted in the development Community including nodejs packages it helps developers understand the potential impact of updating a package”
Global npm Packages: Packages installed globally (npm install -g <package-name>) are typically command-line tools accessible system-wide. Minimize global installations to avoid version conflicts.
“Global packages are typically command line tools or utilities that you want to run from anywhere on your system not just within a specific project”
“to install a package globally you would use the – G or hyphen G or the– Global flag with the mpm install command”
Publishing npm Packages: The process involves setting up a package.json with a unique name, creating an npm account, writing the package code, and using npm publish to share it. Updates require incrementing the version in package.json.
“creating and Publishing your own mpm package can be a rewarding process allowing you to share your work with the wider no. JS community”
“to publish your package to mpm using the command mpm publish”
Part 4: Asynchronous JavaScript
Main Themes: Understanding synchronous vs. asynchronous code execution, and the evolution of patterns for handling asynchronous operations: callbacks, Promises, and async/await.
Key Ideas and Facts:
Synchronous vs. Asynchronous Code: Synchronous code executes sequentially, blocking further execution. Asynchronous code allows other operations to continue while waiting for a task to complete.
“understanding the difference between synchronous and asynchronous code is fundamental in JavaScript synchronous code executes sequentially blocking further execution until the current task is completed in contrast a synchronous code allows other operations to continue while waiting for an asynchronous task to complete improving performance and responsiveness”
Callbacks: Functions passed as arguments to be executed upon completion of an asynchronous operation. Nested callbacks can lead to “callback hell” (deeply nested and hard-to-manage code). Named functions can improve readability of callback-based code.
“a call back is a function that is passed as an argument to another function to be executed once an asynchronous operation is complete”
“nested callbacks which can lead to callback how which is a situation where code becomes deeply nested and difficult to manage this pattern complicates both reading and maintaining the code”
Promises: Objects representing the eventual outcome (success or failure) of an asynchronous operation. They have three states: pending, fulfilled (resolved), and rejected. Promises provide a cleaner way to handle asynchronous logic using .then() for success and .catch() for errors, avoiding callback hell. Promise.resolve() and Promise.reject() create pre-resolved or pre-rejected promises. Promises support running asynchronous operations in parallel using Promise.all().
“JavaScript promises are a powerful tool for managing asynchronous operations A promise is an object that represents the eventual result of an asynchronous operation it can be in one of three states the first being pending so this is the initial State when the promise is still waiting for the asynchronous operation to complete the second state is fulfilled the operation completed successfully and the promise has a value and the third possible state is rejected so the operation failed and the promise hasn’t air”
“replacing callbacks with promises promises help avoid the complexity of nested callbacks by returning promises from functions you can chain asynchronous operations more straightforward using the them method for resolve promises and do catch for errors”
Async/Await: Syntactic sugar over Promises that makes asynchronous code look and behave more like synchronous code. async declares an asynchronous function (which implicitly returns a Promise), and await pauses the execution of an async function until a Promise resolves. Error handling with async/await is done using try…catch blocks.
“async 08 is syntactic suar sugar over promises making asynchronous code look synchronous”
“this keyword allows you to wait for a promise to resolve and get its result you could use it only inside functions marked with the async keyword”
“async this keyword is used to declare that a function is asynchronous it ensures that the function returns a promise”
“for air handling we use try and catch blocks to handle errors when using a sync and a we”
This briefing document covers the foundational concepts and practices discussed in the provided sources, highlighting the setup of a development environment, core JavaScript principles, object-oriented programming, module management in Node.js, and effective strategies for handling asynchronous operations. Understanding these topics is crucial for modern JavaScript development, particularly in backend environments using Node.js.
Frequently Asked Questions on Node.js and JavaScript Asynchronous Programming
1. What are the fundamental differences between synchronous and asynchronous code execution in JavaScript, and why is understanding this distinction important for Node.js development?
Synchronous code executes line by line, and each operation must complete before the next one begins, potentially blocking the program if an operation takes a long time. Asynchronous code, on the other hand, allows the program to continue executing other tasks while waiting for a long-running operation (like reading a file or a network request) to complete. Once the asynchronous operation finishes, a callback function or a promise’s resolution/rejection is handled. Understanding this distinction is crucial for Node.js development because Node.js is designed to handle many concurrent connections efficiently. Its non-blocking, event-driven architecture relies heavily on asynchronous operations to prevent the server from becoming unresponsive when dealing with I/O-bound tasks.
2. How does Node.js utilize modules to organize and encapsulate code, and what are the advantages of this modular approach for building scalable and maintainable applications?
Node.js treats each file as a separate module, helping to organize code into reusable units. Modules can export specific parts of their functionality (functions, objects, classes) using module.exports (in CommonJS) or export (in ES Modules), which can then be imported into other modules using require (in CommonJS) or import (in ES Modules). This modular approach offers several advantages:
Code Organization: It breaks down large applications into smaller, manageable pieces, making the codebase easier to navigate and understand.
Reusability: Modules can be reused across different parts of the application or even in other projects, reducing code duplication and development time.
Maintainability: Changes to one module are less likely to affect other parts of the application, provided the module’s interface remains stable, making it easier to update and refactor code.
Scalability: Well-organized, modular code is easier to scale as new features or functionalities can be added as separate modules without increasing the complexity of the entire system.
Namespace Management: Modules help avoid global namespace pollution by keeping variables and functions within their local scope unless explicitly exported.
3. What is the Node Package Manager (npm), and why is it an essential tool for Node.js development? What are some key commands and concepts associated with npm?
npm (Node Package Manager) is the default package manager for Node.js. It is an essential tool that allows developers to easily share, install, and manage dependencies (third-party libraries and tools) for their Node.js projects. Key commands and concepts include:
npm init: Initializes a new Node.js project and creates a package.json file.
package.json: A file that contains metadata about the project, including its name, version, dependencies, scripts, and more. It’s crucial for managing project dependencies.
npm install <package-name>: Installs a specified package and adds it to the node_modules directory and the dependencies or devDependencies section of package.json.
npm install -D <package-name> or npm install –save-dev <package-name>: Installs a package as a development dependency, typically used for testing or build tools.
npm install: Installs all the dependencies listed in the package.json file.
node_modules: The directory where npm installs project dependencies. It’s typically excluded from version control.
Semantic Versioning (semver): A standard (Major.Minor.Patch) used by npm to manage package versions and specify compatible update ranges using symbols like ^ (caret) and ~ (tilde) in package.json.
Global vs. Local Installations: Packages can be installed locally (within a project’s node_modules) or globally (for command-line tools accessible system-wide using npm install -g <package-name>).
npm publish: Used by developers to upload their own packages to the npm registry for others to use.
4. How does Node.js handle asynchronous operations using callbacks, promises, and async/await? What are the benefits and drawbacks of each approach, and when might you choose one over the others?
Node.js provides several ways to handle asynchronous operations:
Callbacks: Functions passed as arguments to be executed upon the completion of an asynchronous task.
Benefits: Widely supported and the original way of handling asynchronicity in JavaScript.
Drawbacks: Can lead to “callback hell” (deeply nested callbacks) making code hard to read and maintain. Error handling can become complex.
When to use: For simple asynchronous operations or when working with older APIs that don’t support promises.
Promises: Objects representing the eventual completion (resolve) or failure (reject) of an asynchronous operation. They provide a more structured way to handle asynchronicity using .then() for success and .catch() for errors.
Benefits: Improve code readability and maintainability by avoiding callback hell through chaining. Offer better error handling with a single .catch() at the end of a promise chain.
Drawbacks: Can still lead to verbose code with long chains. Error handling needs to be explicitly managed.
When to use: For managing sequences of asynchronous operations or when dealing with APIs that return promises.
Async/Await: Syntactic sugar built on top of promises that allows you to write asynchronous code that looks and behaves more like synchronous code using the async and await keywords.
Benefits: Significantly improves code readability and makes asynchronous logic easier to follow. Simplifies error handling using try…catch blocks.
Drawbacks: await can only be used inside async functions. Can sometimes hide the asynchronous nature of operations, potentially leading to misunderstandings about performance.
When to use: For most modern asynchronous JavaScript development where readability and maintainability are key, especially for complex sequences of asynchronous tasks.
5. What is the significance of the this keyword in JavaScript, and how does its behavior differ in various contexts (e.g., global scope, function context, class methods, arrow functions)? How can issues related to this context be managed?
The this keyword in JavaScript refers to the object that is currently executing the code. Its behavior varies depending on the context in which it is used:
Global Scope: In non-strict mode, this refers to the global object (e.g., window in browsers, global in Node.js). In strict mode, this is undefined.
Function Context (Regular Functions): The value of this depends on how the function is called. It can be the global object (in non-strict mode when called independently), undefined (in strict mode when called independently), the object calling the method (when called as a method of an object), or bound to a specific object using call(), apply(), or bind().
Class Methods: Inside methods of a class, this refers to the instance of the class that the method is called on.
Arrow Functions: Arrow functions do not have their own this context. They lexically capture the this value from their surrounding (enclosing) scope. This makes them useful for callbacks within methods or other functions where you want this to refer to the outer scope’s this.
Issues related to this context can be managed by:
Using arrow functions to preserve the this from the outer scope.
Using bind(), call(), or apply() to explicitly set the this value.
Being mindful of strict mode’s impact on this in regular functions.
When detaching methods from objects, ensure the intended this context is preserved (e.g., using bind()).
6. Explain the concepts of closures, encapsulation, and abstraction in JavaScript. How are these principles implemented and why are they important for writing robust and maintainable code, especially in the context of object-oriented programming with Node.js?
Closures: A closure is a feature in JavaScript where an inner function has access to the outer (enclosing) function’s variables—the scope chain—even after the outer function has finished executing. This happens because the inner function “closes over” its environment. Closures are often used to create private variables and maintain state.
Encapsulation: Encapsulation is the practice of bundling data (properties) and the methods that operate on that data within a single unit (an object or a module). It also involves hiding the internal state of an object and exposing only a public interface. This protects the data from unintended modification and simplifies how the object is used. In JavaScript, encapsulation can be achieved using closures (for data privacy), conventions (like prefixing private members with _), Symbols, WeakMaps, and private class fields (#). Modules also provide encapsulation by isolating the scope of variables and functions.
Abstraction: Abstraction involves hiding complex implementation details and showing only the essential information to the user. It allows developers to use objects or modules without needing to know how they work internally. In JavaScript, abstraction can be implemented through well-defined public interfaces of objects and modules, which internally use private properties and methods (achieved through closures, Symbols, WeakMaps, or private class fields) to handle the complexity.
These principles are crucial for writing robust and maintainable code because they:
Improve Code Organization: They help structure code logically, making it easier to understand and manage.
Enhance Reusability: Encapsulated and abstracted components are more likely to be reusable in different parts of the application or in other projects.
Increase Maintainability: Changes to the internal implementation of an encapsulated component do not affect other parts of the system as long as the public interface remains the same.
Promote Data Integrity: Encapsulation helps protect data by controlling how it can be accessed and modified.
Reduce Complexity: Abstraction allows developers to work with higher-level concepts without being overwhelmed by the underlying details.
In Node.js, which is often used to build complex backend systems, applying these OOP principles helps manage the complexity of the application and ensures that the codebase remains manageable as it grows.
7. What are prototypes and how does prototype-based inheritance work in JavaScript? How do constructors relate to prototypes, and why is understanding the prototype chain important for optimizing memory usage and code reuse in Node.js applications?
In JavaScript, every object has a prototype, which is another object that it inherits properties and methods from. This is the basis of prototype-based inheritance. When you try to access a property of an object, and that property is not found on the object itself, JavaScript looks up the prototype chain until it finds the property or reaches the end of the chain (which is null).
Constructors are functions used to create objects. When you create an object using the new keyword with a constructor function, the newly created object’s internal prototype ([[Prototype]], accessible via __proto__ or Object.getPrototypeOf()) is set to the prototype property of the constructor function.
Understanding the prototype chain is important for:
Memory Optimization: Methods and properties added to the prototype of a constructor are shared by all instances created by that constructor. This means that instead of each object having its own copy of these members, they all refer back to the same ones on the prototype, saving memory, especially when dealing with a large number of objects.
Code Reuse: Inheritance through prototypes allows you to reuse functionality defined on a prototype across multiple objects, promoting a more organized and efficient codebase. You can extend or modify the behavior of objects by manipulating their prototypes.
Understanding JavaScript’s Object Model: A solid grasp of prototypes is fundamental to understanding how objects in JavaScript work and how inheritance is achieved.
In Node.js, where applications often involve creating many objects (e.g., handling numerous requests), leveraging prototype-based inheritance effectively can lead to significant performance improvements and more efficient resource utilization.
8. What are ES Modules and CommonJS, and how do they differ in Node.js? What are the syntaxes for importing and exporting modules in each system, and when might you choose one over the other in a Node.js project?
CommonJS was the original module system used in Node.js. It uses a dynamic approach to module loading.
Exporting: Uses module.exports to export values (can be a single value or an object containing multiple exports) and exports as a shorthand for module.exports.
Importing: Uses the require() function to import modules, typically assigning the result to a variable.
ES Modules (ECMAScript Modules) are the standard module system introduced in ECMAScript 2015 (ES6). They offer a more static and standardized way to handle modules across JavaScript environments (browsers and Node.js).
Exporting: Uses the export keyword to export named bindings (e.g., export const myVariable = …) or a default export (e.g., export default myClass).
Importing: Uses the import keyword to import named bindings (e.g., import { myVariable } from ‘./module’) or the default export (e.g., import myClass from ‘./module’).
Differences in Node.js:
Loading Mechanism: CommonJS is dynamic (modules are resolved at runtime), while ES Modules are more static (module dependencies can be analyzed at parse time, allowing for potential optimizations like tree-shaking).
Syntax: Different keywords (require/module.exports vs. import/export).
Scope: Both provide module-level scope, but ES Modules have stricter scoping rules.
“use strict”: ES Modules implicitly operate in strict mode.
Top-level await: Allowed in ES Modules but not in CommonJS (outside of async functions).
When to Choose:
CommonJS: Historically used in most Node.js projects and is still the default in many older projects or when working with code that primarily uses this syntax.
ES Modules: Recommended for new Node.js projects as they are the modern JavaScript standard and offer benefits like static analysis and better support in modern JavaScript tooling. Node.js has increasingly improved its support for ES Modules, and it’s becoming more common to use them. You can configure Node.js to treat .js files as ES Modules by adding “type”: “module” to your package.json file, or by using the .mjs file extension.
Many modern Node.js projects are transitioning to or already using ES Modules for a more standardized and potentially optimized module management system.
JavaScript OOP Challenges and Considerations
Object-Oriented Programming (OOP), while offering numerous benefits, also presents certain challenges, particularly in its implementation and design. Based on the sources, some of these challenges in the context of JavaScript include:
Challenges with Inheritance:
Inappropriate Relationships: A key challenge with inheritance is ensuring that the subclass truly represents a specialized version of the superclass, adhering to the “is a” relationship. Problems arise when a subclass inherits methods that do not logically apply to it, leading to an inappropriate relationship and potentially bloated or confusing interfaces. For example, if a base Employee class has a code method, it might not logically apply to a Manager subclass.
Inheritance Complexity: Deep inheritance hierarchies can become difficult to manage and understand. The more levels of inheritance, the harder it can be to track where properties and methods are coming from and how changes in one part of the hierarchy might affect others. The sources suggest limiting inheritance depth to maintain manageable code.
Constructor Property Issues: When implementing inheritance using Object.create to set the prototype, the constructor property of the subclass prototype mistakenly points to the superclass constructor. This can cause confusion when creating instances dynamically and requires manually resetting the constructor property to reflect the actual subclass constructor.
Modifying Built-in Prototypes: While JavaScript allows extending built-in prototypes, it is generally ill-advised due to the potential for conflicts with third-party libraries that might rely on the default behavior. Modifying built-in prototypes can also lead to inconsistent behavior and make code harder to maintain and predict, potentially breaking compatibility with future JavaScript versions.
Global Scope Pollution: In JavaScript environments, particularly browsers, defining variables and functions in the global scope (using var at the top level) can lead to namespace pollution. The global namespace can become cluttered, making it difficult to track definitions. Additionally, accidental overwriting of global variables by different parts of an application can cause hard-to-diagnose bugs. Modularity, using techniques like CommonJS or ES6 modules, is essential to mitigate these risks by encapsulating code and avoiding global scope interference.
Managing Private Data: Achieving true data encapsulation, a core OOP principle, has historically been a challenge in JavaScript. While naming conventions (using underscores) and ES6 Symbols offer some level of privacy, they don’t provide complete protection. ES2022 introduced private class fields (using the # prefix) as a more robust solution for ensuring data and method privacy within classes. WeakMap can also be used to store private data, offering the additional benefit of allowing objects to be garbage collected even with associated private data in the WeakMap.
Choosing Between Inheritance and Composition: Deciding when to use inheritance versus composition can be a challenge. Inheritance should ideally represent an “is a” relationship, but over-reliance can lead to complex hierarchies and the inheritance of inappropriate functionalities. Composition, representing a “has a” relationship, often provides a more flexible and robust alternative by building objects from components, reducing dependencies and promoting code reuse through techniques like mixins.
These points highlight some of the significant challenges and considerations when working with OOP principles in JavaScript, emphasizing the importance of careful design, adherence to best practices, and understanding the specific features and limitations of the language.
JavaScript Objects: Concepts and Mechanisms
Let’s discuss JavaScript objects, drawing on the information from the sources and our previous conversation about OOP challenges.
Fundamentals of JavaScript Objects
At its core, a JavaScript object is a collection of key-value pairs. These pairs are also known as properties, where the key is typically a string (or Symbol) and the value can be any JavaScript data type, including primitive values, other objects, or functions. Functions within an object are referred to as methods.
Creating Objects
JavaScript offers several ways to create objects:
Object Literals: The most common way to create a simple object is using curly braces {} to define an object literal, where you directly specify the key-value pairs. For example:
drinkCoffee() { // Syntactic sugar for defining methods
console.log(this.name + ” drinks coffee”);
}
};
Factory Functions: A factory function is a function that returns a new object each time it is called. This can help avoid code duplication when creating multiple similar objects.
Constructor Functions: Before ES6, JavaScript used constructor functions along with the new keyword to create objects, mimicking class-like behavior. Constructor functions use PascalCase for naming convention, and the this keyword is used to assign properties and methods to the new object.
ES6 Classes: Introduced in ES6, the class syntax provides a more structured and cleaner way to define constructor functions and manage prototypical inheritance. It is essentially syntactic sugar over JavaScript’s existing prototypal inheritance model. Classes use a constructor method to initialize object properties and define methods within the class body.
Dynamic Nature of Objects
JavaScript objects are inherently dynamic, meaning you can add, modify, and delete properties and methods at any time after an object’s creation. This can be done using either dot notation or square bracket notation. While using const to declare an object prevents reassignment of the variable to a different object, the contents of the object itself can still be altered.
Iterating Over Object Properties
JavaScript provides several ways to iterate over the properties of an object:
for…in loop: This loop iterates over all enumerable properties of an object, including inherited properties from its prototype chain.
Object.keys(obj): This method returns an array containing the names of all own enumerable properties of the object obj. It does not include inherited properties.
Object.values(obj): This method returns an array containing the values of all own enumerable properties of the object obj.
Object.entries(obj): This method returns an array of [key, value] pairs for all own enumerable properties of the object obj.
Prototypes and Prototypal Inheritance
Every JavaScript object has an internal prototype (accessible via Object.getPrototypeOf(obj) or the older __proto__ property), which is another object or null. When you try to access a property of an object, and that property is not found on the object itself, JavaScript looks for it in the object’s prototype, then in the prototype’s prototype, and so on, up the prototype chain. This mechanism is known as prototypal inheritance, where objects inherit properties and methods from their prototype objects.
Constructor functions also have a prototype property, which is an object that becomes the prototype for all instances created with that constructor. Methods defined on a constructor’s prototype are shared among all instances, leading to more memory-efficient code compared to defining methods directly within the constructor function.
The this Keyword
The this keyword in JavaScript refers to the context in which a function is executed. In the context of object methods, this typically refers to the object that the method is called on. However, the value of this can change depending on how a function is called (e.g., direct function call, method call, using call, apply, or bind). In strict mode, the value of this in a standalone function is undefined, which helps prevent accidental modification of the global object. ES6 classes implicitly use strict mode.
Encapsulation and Data Privacy
Encapsulation, one of the four pillars of OOP, involves hiding the internal state and functionality of an object and exposing only what is necessary. JavaScript provides several mechanisms for achieving data privacy:
Abstraction: Hiding complex implementation details and showing only necessary information to the user. This is often achieved through well-defined public interfaces (methods) that interact with private parts of the object.
Naming Conventions (Underscore Prefix): Historically, using an underscore _ prefix for property names was a convention to indicate that a property was intended for internal use and should not be accessed directly from outside the object. However, this does not provide true privacy.
Symbols: ES6 introduced Symbols, which are unique and immutable primitive values that can be used as object property keys. Properties keyed by Symbols are not easily discoverable through standard reflection mechanisms, providing a form of “soft” privacy.
Weak Maps: WeakMap is a collection of key-value pairs where keys are objects, and values are arbitrary values. Unlike regular Maps, WeakMap allows for garbage collection of key objects even if they are still present as keys in the WeakMap (if there are no other strong references to them). This makes them suitable for storing private data associated with objects without preventing memory leaks.
ES2022 Private Class Fields: ES2022 introduced private class fields and methods using the hash # prefix. These private members are truly private and are only accessible from within the class where they are defined, providing strong data encapsulation.
Inheritance and Extending Objects
JavaScript primarily uses prototypal inheritance for sharing properties and methods between objects. ES6 classes provide a more familiar syntax for defining inheritance hierarchies using the extends keyword. A subclass (or derived class, child class) can extend a superclass (or base class, parent class), inheriting its properties and methods.
The super keyword is used in a subclass constructor to call the superclass constructor and in subclass methods to call superclass methods, allowing for extending or modifying inherited behavior.
Method overwriting allows a subclass to provide its own specific implementation of a method that is already defined in its superclass.
Mixins
Mixins offer a flexible alternative to traditional inheritance for composing objects with multiple behaviors. Instead of inheriting from a single base class, an object can “mix in” functionalities from multiple smaller, focused objects. This can be achieved using Object.assign to copy properties and methods from mixin objects to a target object. Mixins promote composition over inheritance, which can lead to more modular and maintainable code.
Property Descriptors
JavaScript objects have associated property descriptors that define the attributes of each property, controlling how they can be accessed, modified, and enumerated. These attributes include:
enumerable: Determines whether the property will appear during for…in loops and Object.keys().
writable: Determines whether the property’s value can be changed.
configurable: Determines whether the property descriptor can be changed and whether the property can be deleted.
You can get and set these attributes using Object.getOwnPropertyDescriptor() and Object.defineProperty() respectively.
Getters and Setters
Getters and Setters are special methods that allow you to control the access and modification of object properties.
Getters (defined using the get keyword in object literals or class bodies, or Object.defineProperty) are called when you try to access a property, allowing you to execute code and return a computed value.
Setters (defined using the set keyword or Object.defineProperty) are called when you try to assign a value to a property, allowing you to perform actions like validation or logging before the value is actually set.
Getters and Setters provide a way to encapsulate property access and modification, enhancing data integrity and providing a cleaner interface.
Primitive vs. Reference Types
It’s important to understand that objects are reference types in JavaScript. When you assign an object to a variable, you are actually assigning a reference to the object in memory. If you assign that variable to another variable, both variables will point to the same object in memory. Therefore, changes made through one variable will affect the other. This is in contrast to primitive types (e.g., numbers, strings, booleans), which are passed by value, meaning a copy of the value is created when assigned to a new variable.
Memory Management
As we discussed, using prototypes for shared methods is crucial for memory efficiency when dealing with numerous object instances. Instead of each instance having its own copy of a method, they all share the same method defined on the prototype. Additionally, using WeakMap for private data can aid in memory management by allowing the garbage collector to reclaim memory occupied by objects even if they have associated private data in the WeakMap (when there are no other strong references).
By understanding these concepts, you can effectively work with JavaScript objects, leveraging their flexibility and power while also being mindful of best practices for code organization, maintainability, and performance, especially in the context of the OOP challenges we previously discussed.
JavaScript Object Literals: Definition and Use
Let’s delve deeper into JavaScript object literals, drawing upon the information in the provided sources and our previous discussion about JavaScript objects.
An object literal is a fundamental way to create objects in JavaScript. It is defined using curly braces {} and consists of key-value pairs. These key-value pairs represent the properties of the object, where the key is typically a string (or Symbol) and the value can be any valid JavaScript data type, including primitive values, other objects, or functions (which become methods of the object).
Creating Object Literals
You create an object literal by simply using the curly brace notation and defining the key-value pairs within them. Here’s a basic example from source:
let proProgrammer = {
name: “Your Name”,
preferredLanguage: “JavaScript”
};
In this example, proProgrammer is an object literal with two properties: name and preferredLanguage, each assigned a string value.
Defining Properties and Methods
Within an object literal, you can define both data properties and methods.
Properties are defined as key: value pairs.
Methods (functions associated with the object) can be defined in a couple of ways:
Using a traditional function expression:
let myObject = {
myMethod: function() {
// … function body
}
};
Using the more concise syntactic sugar introduced in ES6:
let myObject = {
myMethod() {
// … function body
}
};
Source provides an example illustrating method definition:
Here, writeCode and drinkCoffee are methods of the programmer object literal. The this keyword within these methods refers to the programmer object itself, allowing access to its properties like name.
Dynamic Nature
As we discussed previously, and as implied by the ability to manipulate objects using dot or bracket notation, object literals, like all JavaScript objects, are dynamic. You can add new properties or methods, modify existing ones, or delete them after the object literal has been created. For example:
let myObject = { key: “value” };
myObject.newProperty = “another value”; // Adding a new property
myObject.key = “updated value”; // Modifying an existing property
delete myObject.key; // Deleting a property
Use Cases and Benefits
Object literals are incredibly useful for:
Organizing related data: They allow you to group together a set of variables (properties) and functions (methods) that logically belong together, as seen in the programmer example.
Representing real-world entities or complex data models: You can easily model objects with their attributes and behaviors using object literals.
Creating simple configuration objects: Passing options or settings to functions often involves using object literals.
Returning simple data structures from functions.
Source highlights that by using object literals, you can create versatile and reusable code structures that represent real-world entities or complex data models effectively. They contribute to making your code cleaner and more intuitive to work with by encapsulating related properties and functions within a single organized entity.
Limitations
While object literals are convenient, they have limitations, especially when you need to create multiple objects with the same structure and methods. Source points out that if you need to create multiple programmer objects using the object literal syntax repeatedly, it can lead to duplicated code, making your application harder to maintain. This is particularly true for objects that include methods, as the behavior might be repeated across multiple instances.
Comparison with Other Object Creation Methods
To address the code duplication issue with object literals, JavaScript offers other ways to create objects, such as:
Factory Functions: As mentioned in source, factory functions are functions that return a new object each time they are called, allowing for the creation of multiple objects with the same methods but potentially different property values.
Constructor Functions (and ES6 Classes): These provide a blueprint for creating objects and are particularly useful for implementing inheritance and creating instances of a specific “type” of object, as discussed in sources.
In summary, object literals are a foundational and highly used feature in JavaScript for creating single instances of objects with a clear and concise syntax. They are excellent for organizing data and representing entities but can become less maintainable when you need to create many similar objects, at which point factory functions or constructor functions/classes might be more appropriate.
Let’s delve into Factory Functions in JavaScript, drawing upon the information in the provided sources and our previous discussion about object literals.
A factory function in JavaScript is essentially a function that returns a new object each time it is called. Source explains that the name of a factory function is typically in camel case notation and that it can accept parameter variables. These parameters allow you to customize the values of the object being returned.
Creating Factory Functions
According to source, you implement a factory function as a regular JavaScript function. Inside this function, you define and return a new object literal. Here’s the example provided in source for creating programmer objects:
function createProgrammer(name, preferredLanguage) {
In this example, createProgrammer is a factory function that takes name and preferredLanguage as parameters and returns a new object literal with these properties and the writeCode and drinkCoffee methods. Source also demonstrates a more concise syntax for the returned object literal:
function createProgrammer(name, preferredLanguage) {
Source also provides an example of a factory function for creating grocery list items:
function createGroceryItem(name, quantity) {
return {
name,
quantity,
display() {
console.log(this.quantity + ” times ” + this.name);
}
};
}
Benefits of Using Factory Functions
Source explicitly states the benefit of factory functions is that they reduce code duplication and the need to copy and paste when you need to create multiple objects with similar structures and behaviors.
Consider the limitation of object literals we discussed earlier. If you needed to create several programmer objects, using object literals would require you to duplicate the writeCode and drinkCoffee methods in each object, making the code inefficient and harder to maintain. Factory functions solve this problem because the methods are defined once within the factory function and are included in each new object it returns. This makes the codebase cleaner and more manageable.
Source further elaborates that factory functions provide an efficient way to create new objects. The parameter variables allow for customizing the values of the returned object.
Usage
To use a factory function, you simply call it like any other function, passing in the necessary arguments. Source provides the following examples:
newProgrammer.writeCode(); // Output: Alice writes JavaScript code
For the grocery list item factory:
const newItem = createGroceryItem(“bananas”, 5);
newItem.display(); // Output: 5 times bananas
In summary, factory functions are a valuable pattern in JavaScript for creating multiple objects with shared behavior without duplicating code. They enhance maintainability and provide a cleaner way to instantiate objects compared to repeatedly using object literals, especially when those objects have methods. They offer a step towards more structured object creation in JavaScript.
JavaScript Constructor Functions
Let’s discuss Constructor functions in JavaScript, drawing upon the information in the provided sources and our conversation history about object literals and factory functions.
In traditional JavaScript, before the introduction of the class syntax in ES6, constructor functions were the standard way to mimic class-like behavior and instantiate new objects. Source explicitly states that JavaScript used functions and the new keyword to achieve this, a technique known as Constructor functions. The ES6 class syntax, as source notes, is essentially syntactic sugar over this underlying prototypal inheritance mechanism.
Defining Constructor Functions
According to source, constructor functions are defined using the function keyword. By convention, their names are written in PascalCase, where the first letter of each word in the name is capitalized (e.g., Programmer, GroceryItem).
Here’s an example from source of a constructor function for creating programmer objects:
And here’s a constructor function for a grocery item from source:
function GroceryItem(name, quantity) {
this.name = name;
this.quantity = quantity;
this.display = function() {
console.log(this.quantity + ” times ” + this.name);
};
}
The new Keyword
The crucial aspect of constructor functions is how they are used to create objects. You instantiate a new object and call a constructor function using the new keyword.
When you use new followed by a constructor function:
A new object is created in memory.
The this keyword inside the constructor function is bound to this newly created object.
The code inside the constructor function is executed, allowing you to assign properties and methods to the this object.
If the constructor function does not explicitly return an object, the newly created object is returned implicitly.
Source provides an example of creating instances using the new keyword:
const newProgrammer = new Programmer(“Alice”, “JavaScript”);
newProgrammer.writeCode(); // Output: Alice writes JavaScript code
const newItem = new GroceryItem(“bananas”, 5);
newItem.display(); // Output: 5 times bananas
The this Keyword
As mentioned above, within a constructor function, the this keyword refers to the specific instance of the object being created. This allows you to assign properties (like this.name = name) and define methods (like this.writeCode = function() {…}) that will belong to each individual object created with the constructor.
The constructor Property
Every object in JavaScript has a special property called constructor. This property references the function that was used to create the object via the new keyword. Source illustrates this:
This constructor property can be useful for checking the type of an object, especially in more complex codebases.
Comparison with Object Literals and Factory Functions
Object Literals: As we discussed, object literals are excellent for creating single, specific objects. However, when you need to create multiple objects with the same structure and methods, they lead to code duplication. Constructor functions (and factory functions) address this by providing a reusable blueprint.
Factory Functions: Both constructor functions and factory functions serve to create multiple objects. However, they differ in their approach:
Constructor functions are called with the new keyword, and they implicitly return the newly created object. The this keyword is central to their operation.
Factory functions are regular functions that explicitly return a new object literal. They don’t require the new keyword, and the concept of this refers to the scope in which the function is called unless explicitly bound. Source mentions that factory functions ensure each object has its unique properties but can share the same methods. We will likely discuss how method sharing is typically implemented with constructor functions (using prototypes) later.
In summary, constructor functions provide a way to create multiple objects with a defined structure and behavior. They rely on the new keyword to instantiate objects and bind the this keyword to the new instance. They were a fundamental pattern in JavaScript for creating objects that share properties and methods before the introduction of the more class-like syntax in ES6.
JavaScript Essentials Course
The Original Text
learn JavaScript Essentials with this course that covers everything from objectoriented programming fundamentals to Advanced asynchronous Techniques Steph Garcia will teach you critical Concepts including objects prototypes es6 classes modules and the node ecosystem while building practical skills through Hands-On examples welcome to JavaScript Pro the comprehensive course designed to take you from intermediate to advanced level JavaScript JavaScript is everywhere from Dynamic websites to mobile apps mastering it is the key to unlocking opportunities as a developer this isn’t just another JavaScript course it’s a step-by-step guide into the features of the JavaScript language this course is for developers looking to level up their skills what truly sets this course apart is our teaching style I use the active recall technique popularized by Cal Newport the author of deep work and a computer science Professor this technique engages your brain in a way that helps you truly internalize concepts by actively practicing how to retrieve them from memory in every section you’ll encounter carefully crafted study questions designed not just to teach but also to challenge you we’ll go over a possible answer for every single question helping you fill in any gaps of your understanding plus there’s an accompanying ebook and PDF that includes all the questions and answers so you can review and reinforce your knowledge anytime this course is designed to actively engage all learning styles visual auditory reading and kinesthetic so that no matter how you learn best you’ll find an approach that works for you every lesson is structured to utilize multiple senses and areas of the brain to maximize retention and understanding we start with the fundamentals of advanced JavaScript covering objectoriented programming prototypes es6 classes and modules you’ll dive into practical tools like Babel webpack and node.js to build projects that mirr world world scenarios my goal is to teach you how to think like a professional developer by the end of this course you’ll have the skills confidence and mindset needed to tackle complex JavaScript problems Ace job interviews and have the fundamental programming skills needed to build apps so let’s go over what you’ll learn in the nine sections of JavaScript Pro intro to Advanced topics we start with the essentials an introduction to Advanced JavaScript Concepts and how this course is structured to maximize your learning you’ll set up a professional development environment and gain an overview of the key skills you’ll develop throughout the course this section lays the foundation for a smooth productive learning experience objects Master the core principles of objectoriented programming also referred to as o including the four pillars which are encapsulation inheritance abstraction and polymorphism you’ll learn how to create and manipulate objects using different approaches like object literals factories and Constructors by the end of the section you’ll understand how to manage properties use Getters and Setters and handle Concepts like abstraction and private properties which are all critical for building scalable and maintainable code prototypes discover how javascripts prototypical inheritance Works under the hood explore key Concepts like inheritance property descriptors and the difference between prototype and instance members you’ll also learn when and why to avoid extending built-in objects and how to iterate through prototype members effectively prototypical inheritance build on the previous section with a deep dive into creating and managing your own prototypical inheritance hierarchies you’ll learn how to reset Constructors call Super Constructors override methods and even Implement polymorphism by the end of the section you’ll know how and when to use inheritance in real road projects and how to enhance functionality with mixins es6 classes transition from traditional prototypes to Modern es6 classes this section covers class syntax inheritance and static methods you’ll also dive into advanced topics like using symbols and weak maps for private members hoisting and Method overwriting these are the tools that will make your JavaScript cleaner more maintainable and align with modern best practices es6 tooling Master the tools that power modern JavaScript development you’ll learn how to use modules both commonjs and es6 as well as how to optimize your workflow flow with Babble and webpack these tools will allow you to write cleaner more efficient code and ensure compatibility across different environments which is a must have for professional developers node module system get started with nodejs and understand how it enables JavaScript to run on servers you explore node.js architecture the module system and key built-in modules like path OS file system and events by the end of the section you’ll know the fundamentals of node.js required to create powerful scalable backend systems and understand how the module Raper function and event driven architecture work node package manager learn how to manage project dependencies like a pro this section covers everything from creating and managing package.json files to installing updating and Publishing packages you’ll also explore semantic versioning and best practices for working with global and local packages these skills are crucial for maintaining efficient collaborative development workflows asynchronous drop JavaScript in this section we will cover one of the most important aspects of JavaScript asynchronous programming learn the difference between synchronous and asynchronous code and how to manage async operations using callbacks promises and async await you’ll also explore patterns for handling callback how running promises in parallel and creating subtle promises this section will give you the confidence to write efficient non-blocking code for World Ro applications so how can this structure work for you each section is designed to build in the laughs creating a seamless Learning Journey that connects theoretical knowledge with practical applications whether you’re preparing for a job interview building your own mobile app or simply aiming to master JavaScript this course will help you with the tools confidence and expertise to achieve your goals level up your career with JavaScript Pro enroll today on Steven codecraft tocom and let’s take your skills to the next level in this video I’ll will guide you through the resources and material tutal that will help you get the most out of your learning experience on Steven codecraft docomo course so if I scroll down here and click Start Learning this will navigate to the course dashboard so here on the course dashboard you can see a button that says to start the video course and if we scroll down we can also see links for the course materials so let’s first click into the video course so we can see that interface so on the left we see the videos so here if I select this particular video I scroll down we can see the different sections now I’ll press play to start the video course so I’ll pause it for now and let’s look at the different options that we have so we have an option to show the subtitles we also have a settings icon where we can adjust the speed so if the video is going too fast you can always adjust it so let’s scroll ahead up here so for each video Lesson I have an active recall study section this helps mimic a technical phone screen interview and also helps you understand where you have gaps in your knowledge so play this so here I will ask a open-ended question Focus and how does it organize software designed after as it you’ll see this text that says to pause the video and answer so manually pause the video and try to answer it in your own words I’ll press play again and then I will provide a sample answer for this question the main focus of object so after you hear the answer don’t worry about memorizing it for btim it’s just to help you understand it in case you struggled with putting in your own words so after you watch the video click on the button that says complete and continue so after you do that you will see a check mark next to this video Lesson and then we’ll move on to the next video in the course so let’s go back to my courses now that you’re more familiar with the video section of the course let’s go back to the dashboard for JavaScript Pro now let’s discuss the course materials so scroll down and you see these different links so for the first link is the code for the course so this section contains the completed code for the course in a GitHub repository so this includes the finished projects and examples that will be building together these resources are designed to help you see the end goal and provide a reference for what your own code should look like as you progress you can use this code as a guide to troubleshoot and refine your own projects but remember the real learning happens when you write the code yourself there’s also another link for the starter files so these files are neatly organized into folders with clear name and conventions to match each video in the course so we’ll click into one of these folders in this case the object section and here you can see different files corresponding to each video Lesson so you can click on this green button you can either clone the project from your terminal or click on download zip and you can open that in s code there’s also an ebook in the course section and this is a 600 page comprehensive ebook and it covers all the topics that we’ll discuss in the video lessons so I strongly encourage you to read the relevant section of the ebook before watching the associated video I’ll scroll down here so you’re more familiar with what the ebook looks like so here we have the introduction and discussion of objectoriented programming So reading the material ahead of time primes your brain for what’s coming in the video making it easier to follow along and retain the information there’s one more ebook in the course materials which is the active recall study questions so this is to ensure that you solidify your knowledge and prepare for worldw applications and Technical phone screen interviews so this PDF contains all of the active recall study questions that we will go over in the videos and this is to test your understanding of key Concepts and build a solid foundation in JavaScript programming let’s scroll here so you’re more familiar it looks like so these are all the questions for section two so you go through each of these and try to answer in your own words and don’t worry about memorizing it for btim of the answer that I provide then you can scroll down so if you struggle with answering that I provide a sample answer so I highly recommend that you take the time to answer these questions even if you’re unsure about an answer the process of thinking about it and putting in your own words will strengthen your understanding and of course you can always refer back to the ebook or the video for clarification these course materials are here to support you every step of the way by engaging with them which includes the finish code the starter files the ebook and the study questions you’ll set yourself up for success and gain a deep lasting understanding of JavaScript to start programming JavaScript there are two essential tools you need to install node.js and visual studio code so what is no. JS this is a powerful runtime environment that lets you run JavaScript outside the confines of a web browser it’s what enables you to build and run JavaScript applications on your computer including server side project while you could just run JavaScript in your browser for this course you will be using node.js to execute our programs the second tool is Visual Studio code otherwise known as vs code developed by Microsoft this is an integrated development environment or IDE for short and this is where you’ll spend most of your time writing testing debugging and running your code it’s a versatile desktop application used by developers worldwide and we’ll be using it throughout this course both node.js and visual studio are free and easy to install installing node.js Begin by opening your browser and heading to nodejs.org once you’re on the side click the download node.js LTS stands for long-term support downloading this version is recommended for most users because it’s the most stable and well supported version of node.js once downloaded open the installer and follow the onscreen instructions the default settings are suitable for most users so you can proceed with them unless you have specific preferences installing Visual Studio code next we’ll install our IDE navig to code. visual studio.com in your web browser click the download button for your operating system vs code is available for Windows Mac and Linux after downloading run the installer like with nodejs the default installation options will work perfectly for our purposes so now once you have installed both nodejs and visual studio code click to open up vs code after you click it you will see the welcome page then open up finder or File Explorer for your windows and create a new folder now this will be the folder where we place our code so I’ll just name it project now the name of the folder doesn’t matter then I can click and drag it into V s code this will open up the project now to add a new file to our project I can click on this icon and I can name it code. JS so the name of this file doesn’t matter but the file extension does so now we can write our first line of code and I’ll say console.log then in single quotes I’ll say hello world and then I’ll end it with a semicolon notice as I’m typing this file has not been saved yet and so I see a circle indicating that I have unsaved changes so to save it I can do command s or on Windows it would be control s so now if I want to actually execute this file I can do file appearance and then panel to open up the integrated terminal in vs code now there’s also a shortcut I can do control and back tick so if you don’t use the back tick character often it’s located on the left hand side of your keyboard above the tab key so I can do control and back tick to toggle this open so I’ll be using node to execute this program so I’ll type node and then the name of our file which is code. JS so here we see this value hello world is log to the console so I’ll close this now vs code offers a lot of features and a lot of ways to customize it before this course we’ll just be covering the basics that you need to get started so on the left hand side is the activity bar where we see a list of icons the topmost icon is the folder icon and we can use it to toggle our project to see the folders and files within it next is the search icon and we can use this to search find and replace text so for example let’s say if I do hello enter we see that this text is found in our code. JS file so close that the next one is our source code icon and this is used to keep track of the changes in our project as well as collaborate with other developers using get ver control next is the run and debug icon you would use this when setting break points in your code and debugging it if there are errors next is the extensions icon this gives you access to the extensions Marketplace this enables you to install additional features to VSS code to improve your productivity and help you customize vs code to your needs now the icons on the bottom is for your account and to adjust your settings now on the bottom of the screen is the status bar here in Blue on the side you will see any errors or warnings in your code and on the right side I see the line number that I’m on for my current file and I also see the programming language being used so let’s say if I wanted to add another file to my project rather than always having to click on this icon I can use a keyboard shortcut of command and N or control and n on windows open up a new file and on the bottom right we see that this is identified as plain text so now if I want to save this file as a Javascript file I can do command s and I can name it as second program. JS and now in the bottom right we see that vs code can identify that this is a JavaScript file the next thing I want to cover is the command pallet you can access the command pallet by going to view and then command pallet now another way to do that is with the keyboard shortcut of command shift and P it will be control shift and P on Windows now the command pallet is very important as it is the control center for all commands in VSS code from here we can also adjust the color theme that we use so I click on color theme and as I scroll up and down we can see different color themes for my code editor you can also access additional themes we going to the very top clicking on browse additional color themes allowing you to search through different options for this course I’ll just stick to the standard Visual Studio One now to make the text larger you can do command and plus or control and plus on Windows and also command minus or control minus in order to make the text smaller so this is a quick overview of VSS code teaching you the basics that you need for this course so for this course there are two vs code extensions that I suggest and that we will be using throughout this course so click on the icon for extensions and type in Live server then you can install this extension and we’ll utilize it later in the course now this extension live server essentially makes it easy for us to have hot reloading so when we write our code we can actually see those changes reflected in a web browser then another extension that we’ll be using for the early part of this course is quoka you type in so select this one and then install it this allows us to see the output of our JavaScript without having to constantly run it in our terminal before we get started if you’re interested in supporting my courses and projects you can follow me on my new YouTube channel and Instagram at stepen codecraft you can also explore my courses at Steven codecraft tocom and if you’re looking to enhance your health and fitness routine check out my workout and meal planning app at fitfuel planner.com the app offers over 100 recipes workout plans meal plans and a grocery list feature it’s designed to make tracking your calories and macronutrients straightforward and stress free I appreciate your support and I’ll see you in the next section objectoriented programming or o op is a programming Paradigm built around the concept of objects at its core oop organizes software design around data or objects rather than focusing solely on functions and logic objects are instances of classes which serve as blueprints for creating and managing data and behavior a class can encapsulate both the data often referred to as attributes and the functions known as methods that operate on that data this combination makes it easier to group related functionality and data into a single modular structure one of the key benefits of oop is how it promotes modularity and code reusability by designing software in a way that mirrors Ro World objects and their interactions o op helps developers create systems that are easier to understand maintain and extend languages like JavaScript python Java and C are just a few examples of programming languages that support oop providing the tools to create and manipulate objects effectively oop is especially useful for managing the complexity of large software projects making it a preferred approach for many modern applications [Music] what does object orent programming focus on and how is it different from just using functions object orent programming also referred to as oop focuses on organizing code around objects which represent data and the actions that can be performed on that data this is different from just using functions where the focus is primarily on writing step-by-step instructions or logic to solve problems without grouping data and behavior together objectoriented programming or o op is a programming Paradigm that focuses on objects rather than functions this approach organizes software design by grouping related data and behavior into self-contained units called objects at the heart of oop are its four foundational principles I’ll explain each of these principles up front so you’re familiar with them as we begin throughout the course you’ll see examples that clarify these abstract ideas so these four principles include abstraction polymorphism inheritance and encapsulation first let’s discuss abstraction abstraction involves hiding the complex implementation details of an object and exposing only what’s necessary this simplifies how we work with objects allowing us to focus on their functionality without needing to understand all the intricate details behind the scenes polymorphism polymorphism means many forms and this allows objects to be treated as instances of their parent class rather than their specific class this enables methods to behave differently depending on the object that’s calling them making your code more flexible and adaptive inheritance in inheritance allows new objects or classes to take on properties and behaviors of existing ones this reduces code duplication and promotes reusability and makes it easier to maintain consistent design across your application encapsulation encapsulation combines data and the methods that manipulate it into a single self-contained unit referred to as an object by restricting direct access to this data encapsulation and ures better control security and reduces the risk of unintended interference these four principles abstraction polymorphism inheritance and encapsulation can be remembered using the acronym API transitioning from procedural programming before oop became widely adopted many programs were written using procedural programming this approach divides the program into functions that operate on variables while simple procedural programming can create significant challenges as projects grow such as code duplication and interdependencies so code duplication refers to repeatedly copying and pasting similar code across functions leading to redundancy interdependencies refers to changes in one function can inadvertently break others creating a web of interconnected issues often referred to as spaghetti code objectoriented programming addresses these issues by bundling related data and behavior into objects within an object variables are known as properties and functions are called Methods why o Matters by adopting oop principles you can write more modular maintainable and scalable code o simplifies interactions between different parts of your application reduces the risk of errors and Mak your code easier to extend and adapt to Future requirements whether you’re managing a small script or a complex system o provides the structure and Clarity needed for professional software development this lesson provided a highlevel overview of the four core principles of oop which can be remembered using the acronym API standing for abstraction polymorphism inheritance and encapsulation throughout this course we’ll explore more practical examples of of each of these foundational principles in [Music] detail what is the main focus of objectoriented programming and how does it organize software design the main focus of object or programming also referred to as oop is on objects which group related data and behavior into a single unit this helps organize software design by bundling properties and methods together making code easier to manage understand and reuse what is abstraction in oop and how does it simplify working with objects abstraction oop means hiding the complex details of how something works and only showing what is necessary it simplifies working with objects by letting you use their functionality without needing to understand all the behind the scenes implementation how does polymorphism make code more flexible and adaptable in oop polymorphism makes code more flexible and adaptable by allowing the same method or function to work in different ways depending on the object it is used with this reduces the need for repetitive code and makes it easier to handle different types of objects in a consistent way what is inheritance in oop and how does it help reduce code duplication inheritance in oop is a way for one class to use the properties and methods of another class this helps reduce code duplication by allowing you to reuse existing code in new classes instead of writing it again what does encapsulation do in oop and why is it important for control and security encapsulation and O bundles data and the methods that work on it into a single unit called an object and it restricts direct access to the data this is important for control and security because it ensures that data is only modified in controlled ways reducing errors and preventing unintended interference how does oop address the challenges of procedural programming such as code duplication and interdependencies oop addresses challenges like code duplication and interdependencies by organizing code into objects that combine data and behavior this reduces redundancy by reusing code through inheritance and makes programs easier to manage by keeping related functionality within self-contained objects reducing the risk of unintended interactions between parts of the program in JavaScript an object can be defined using curly braces which signify an object literal an object literal is a way to organize data using key value pairs so here’s you can declare an empty object so we can use the let keyword and I’ll name the object Pro programmer let’s assign this to an object literal I’ll give it a key of name and the value of my name I’ll add another key for preferred language and I’ll set that to JavaScript now I’ll Define a method which will utilize these two properties so name this write code and set that to an anonymous function so this will console.log use a template string this.name writes this. prefer language code and I’ll end it with a semicon now I’ll Define another method and I’ll use syntactic sugar for cleaner syntax so I’ll say drink coffee then open and closing parentheses then I will console log this. name drinks coffee so this shows different syntax that you can use to define methods within an object literal and I will end this with the semicolon now I can call programmer. write code control and back tick to bring up the terminal let’s navigate to where this file is so it is in objects and here I’ll do node and I name this file three object literals JS and here I see it logged these property Val vales so in this instance the programmer object literal has four members so it has two properties the name and the preferred language and has two methods write code and drink coffee so this structure allows us to encapsulate related properties and functions within a single organized entity making our code cleaner and more intuitive to work with by leveraging object literals you can create versatile and reusable code structures that represent rward entities or complex data models effectively what is an object literal and how would you create one an object literal is a data structure in JavaScript that allows you to Define key value pairs it essentially enables you to group together variables and functions in the context of an object it will be referred to as properties and methods and you would create one by using curly braces to help reinforce this concept your exercise is to create a simple JavaScript object literal representing a grocery list item this object should have the properties of quantity and name along with a method display that logs the quantity and the name to the console in this format so to demonstrate how you can implement this I can use the cons keyword and I’ll name it grocery item could assign that to an object literal with the key of name I’ll just set that to appps and the key of quantity I’ll set that to four and our method so that will be display console.log back ticks so I’ll say this. Quantity times this. name end it with the semicolon and we’ll close our object literal with a semicon then I can call grocery item. display I can just log this out and I see the expected [Music] output so suppose you need to add another programmer to your team using the object L syntax repeatedly can lead to duplicated code which makes your application harder to maintain this is especially true for objects that include methods indicating that the object has Behavior which may be repeated across multiple instances so let’s consider this object L that we created in the previous lesson if we need to create multiple programmer objects it will be inefficient and air prone to copy and duplicate all this so a more scalable solution is to use a factory function so a factory function is a function that returns a new object each time it is called ensuring that each object has its unique properties but shares the same methods so here’s you can Implement if I name it function and I want name it create programmer so now we’ll specify two parameter variables the first will be name and the second will be prefer language then we’ll return an object literal we do name prefer language we’ll do write code for the method and we can just copy this then the other method is drink coffee and once again we’ll just copy this console log statement and since it’s is a function we don’t have to end it with the semicolon so we can now create a new programmer simply by calling this function so I’ll scroll down so we can see it I’ll say const new programmer equal to create programmer pass in the name Alice and JavaScript as the preferred language so now when I call a new programmer recode let’s pull out the panel and I’ll scroll down I’ll list it out and so I’ll do node I’ll just copy the name of this file and I’ll output it and here we see Alice writes JavaScript code so using Factory functions in this way helps avoid code duplication and simplifies maintenance making your code base cleaner and more manageable [Music] what are Factory functions and why would you use [Music] them Factory functions provide an efficient way for us to create a new object so the name of the function will be in camel case notation and it can accept parameter variables these parameter variables can help customize the values of the object being returned the benefit is that it reduces code duplication and the need to copy and paste [Music] create a factory function which returns a new grocery list item the parameters should be name and quantity so this is the grocery list item which we created in the previous lesson so rather than having to duplicate this we create our Factory function so I say create grocery item and this accepts name and quantity as parameter variable this returns a new object literal it will be name quantity and for the method we can just copy this and paste it here we can end this with a semicolon and so now if we wanted to create a new item we can say h new item is equal to create grocery item we’ll say bananas end up with the S and we’ll just say five so I’ll scroll down we can call new item. display so let’s bring up the terminal and I’ll run it again and here we see the quantity of five [Music] bananas in traditional JavaScript there are no native classes as found in languages like Java or C instead JavaScript uses functions and the new keyword to mimic class life Behavior which is a technique known as Constructor functions this approach was the standard before es6 introduce class syntax as syntactic sugar to simplify object creation and inheritance we willover es6 and that syntax later in the course but for now here’s an example of a Constructor function for creating programmer objects so here I’ll just write a comment to say the lesson and we’ll start up quok so I bring up the command pallet with command shift and P or control shift and P and I will say quoka start on current file so you don’t see this just type in quok select that so now we can see it in our output without having to run node in the terminal so use the function keyword and we use Pascal case for naming our Constructor function and it accepts two parameters which is the name and the preferred language of the programmer language then I’ll use the this keyword which means this current object set it to the name then the preferred language now let’s Implement our methods so this. write code is set to the anonymous function console.log back TI for our template string and I’ll say this.name writes this. preferred language code we end this with the semicon and the anonymous function I’ll say this dot drinks coffee set that to Anonymous function console.log I’ll say this.name drinks coffee just to demonstrate the centx Now to create an instance of this object and to call this Constructor function we use the new keyword so I’ll say con new programmer equal to new programmer then we pass in our arguments I’ll pass an ALICE for the name and on JavaScript as the preferred language now I can call new programmer. write code save that and here we see the output Alice writes JavaScript [Music] code what is a Constructor function a Constructor function is used to instantiate a new object in JavaScript so for the name of convention you would name the function using Pascal case and for assigning the properties and for the methods you would use the this keyword which references this object or the current [Music] object so now for the exercise create a Constructor function for the grocery item so to implement that once again we use our function keyword and we use Pascal case so the first character of each word is capitalized this takes in two parameters the name and the quantity or this keyword with this object just assign this to the quantity now for our display method this. display set that to an anonymous function console.log back TI this. quantity times this.name end that with the semicolon so now we’ll create instance of the grocery item and we call this Constructor function with the new keyword so say const new item is equal to new grocery item for the name we’ll say bananas and the quantity of five so now let’s call this display method so that be new item. display save that and here we see the output which is five bananas every object in JavaScript includes a special property known as Constructor this property references the function that was used to create the object via the new keyword for instance we consider our Constructor function for a programmer object here we use the new keyword to call this function so if we wanted to find out which Constructor function created this object we can access that via its Constructor property so let’s console log that so I’ll say new programmer. Constructor now when we log that in the console so this file is named Constructor property. JS so this will output the programmer function confirming that new programmer is an instance of this programmer Constructor function so this property is particularly useful for confirming the type of object you’re working with especially when dealing with complex code bases that involve multiple Constructors and [Music] prototypes in JavaScript functions are treated as objects this means that like any object a function can have properties and methods and it can be assigned to variables or passed as arguments to other functions so let’s consider a simple function I just name it add and it takes in two numbers num one and num two and it simply Returns the sum of these values so you can assign this function to another variable effectively creating a reference to the original function so I ad do cons if I just name this n and assign that to add now n will reference this function as fun funs are objects in JavaScript so now can actually call that function console. log with this reference n so I can say N I can pass in two and two so I’ll expect the output of four so starting up CA I see that the output is four so as an object the function add has properties and methods for example the length property of a function returns a number of its expected arguments so I were to do console.log of add. length we get the value two as there are two parameter variables so to further illustrate how functions are objects consider creating a function using the function Constructor so I can name that with const programmer Funk equal to new function taking in the name and I’ll use back six so this.name assign to name and to find a method write code assign to an anonymous function console.log code in JavaScript so let’s instantiate an instance so I can say cons and I’ll just call this programmer is assigned to new programmer Funk and I’ll pass in my name as the argument so now let’s call this method right code programmer WR code and here we see our expected output so this lesson shows the unique nature of functions in JavaScript by understanding that functions are indeed objects you gain a deeper understanding into the flexibility and capabilities of JavaScript as a programming [Music] language so for your exercise create a function named calculate price so this function will accept two parameters a grocery item object and a price which is just a number so in that function simply return the price times the quantity of the grocery item so based on our previous lesson we created this Constructor function to create a grocery item and we instantiated a new item so we want to create the function calculate price which accepts a grocery item and a price and we simply return the price Times Grocery item quantity so we want to assign this function name to a variable to demonstrate that functions or objects in JavaScript so we do const perform calculation is assigned to calculate price so now we can invoke it with this reference so let’s do console.log perform calculation so for the first argument we’ll pass our grocery item and we’ll pass 25 cents so here we see the output in quoka is 125 JavaScript supports eight different data types which include seven primitive types and one complex type the Primitive types are are number string Boolean big int undefined null and symbol the eth data type is object which also encompasses arrays and functions understanding the distinction between these types is crucial due to how they are allocated and managed and memory so to demonstrate primitive types these are passed by value so when you work with primitive values these are passed by copy so this means if you assign a variable to another containing a primitive value the new variable gets a copy of that value so altering one will not affect the other because each variable holds its own unique value in a separate memory location so find sanche let a initialize that to the value of 10 and I initialize B and I assign that to a b will get a copy so they are not referencing the same data in memory so if I do a and I Reign that to 20 let’s start qua console log this conso loog the value of a and we’ll cons out the value of B here we see they are different values so now let’s consider reference types which are passed by reference so on the other hand reference types like objects are handled differently so they are passed by reference meaning both variables point to the same object in memory thus changes made in one variable are reflected in the other so say if I assign a and assign it to an object with the value of 20 then if I assign B to a they now reference the same object in memory so if I update a. value to be 100 this will be reflected in both of the references so let me just copy these console log statements and output them here we see they are referencing the same object so in JavaScript primitive values are copied by value meaning they do not affect one another when changed now objects which include arrays and functions are copied by reference meaning changes to One affect any other variable referencing the same object this fundamental understanding helps in managing how data is passed around round in your programs ensuring fewer surprises and more predictable code Behavior what are primitive values and what do they pass by primitive values refer to simple values such as string number booleans and they are passed by copy what are object values and what are they passed by object values refers to key value pairs this also includes arrays and they are passed by [Music] reference so objects in JavaScript are inherently Dynamic which means that you can add or modify their properties and Methods at any time after their creation using the cons keyword with an object declaration ensures that the variable cannot be reassigned to a different value however the contents of the object it points to such as its properties and methods can still be altered or extended so consider the following example find Stan a person object and I give it the key of name and the value of my name let’s end it with the semicolon Now by console log this console.log of person now let’s start up gu so bring our Command pallet start on current file here we see it just outputs our object now if we want to add properties we can do so using either dot notation or square bracket notation so if I use dot notation first I can say person. favorite food assign that to tacos and I’ll just copy this console log and we output it just to demonstrate that I have dynamically added this property and here we see this contains the two properties for the name and favorite food now let’s use the other syntax which is the square bracket syntax and I’ll call this favorite ice cream and let’s just assign that to chocolate now let’s paste our console log statement and here we see our object has been updated now we can also use the delete keyword which will delete a property so if I do delete person favorite ice cream and let’s paste this again and here we see our object has been updated dynamically again deleting the property of favorite ice cream now let’s add a method so I can say person. e let’s assign this to Anonymous function here I’ll say console.log with back ticks and I can say this. name eats this. favorite food and then with the semic so now let’s invoke this method that we’ve added dynamically so I’ll say person. save that and if I look here let me expand this we see Steven eats tacos is the output so this ability to modify objects is both powerful and flexible allowing us to adapt objects to changing requirements or conditions dynamically however it also means that you need to manage objects carefully to avoid unintended side effects from these changes explain in your own words how are objects Dynamic objects in JavaScript are dynamic because you can change and mutate the properties and methods of the object after it has been [Music] initialized so for your exercise create an object with the grocery item Constructor function then dynamically add the property of grocery a so here we have this grocery item Constructor function let’s instantiate an instance of it so we can do that with const new item call the new keyword grocery item we’ll name this bananas the quantity of five now we want to dynamically add a new property so I can say new item do grocery aisle and I’ll set this to the produce section now let’s just console log this console. log of a new item and here we see we have dynamically added the property of grocery [Music] aisle in JavaScript different Loops offer various ways to iterate over collections like arrays and objects for arrays we can use the four of loop so the four of loop is ideal for ating over array elements so if we do let numbers and I assign this to an array of 1 2 3 4 and 5 then if I just do four con element of numbers then console. log of element here we see the output is just each of these elements now for objects we can use the forend loop so the forend loop allows you to iterate over the keys of an object and this is useful for accessing values when you know the structure of the object so I can do con dog and instantiate this object with the name of Max the age of five and so the eye color of blue we’ll end this with the semicolon now we can use our 4 n Loop so four and I can say cons key in the dog object now I can do console.log of dog and access the key with square bracket notation and here I see this output the associated values for each of the keys so besides these two traditional Loops JavaScript provides methods to retrieve the keys values and key value pairs directly from objects which can be iterated over with the four of loop so let’s say if I want to get the keys I can do cons Keys equal to object. keys of the dog object so now I do const key of keys I can do console about log of key and here this will output all the keys of this object likewise I can do the same with the values so cons values equal to object. values of the doc object now for cons value of values console.log each of the values so now this outputs the associated values now we can also enumerate over the key value pairs with object. entries so I can do const entries of object. entries pass this object in now I can do four F entry of entries now here I can do console.log and I’ll use back ticks because I’m going to use interpolation the key which I can access at the first index so that be index is zero and the associated value which would be entry at the index of one so we can save this and said object is supposed to be dog as our object so here are the outputs the associated key value pairs for each of the properties in the dog object so these methods provide a powerful and flexible ways to handle objects in JavaScript they simplify the process of working with objects properties it makes your codee cleaner and more efficient how can you enumerate over the properties of an object there are different ways toate over the properties of an object one way is you can use the fourin loop to iterate over the keys of an object we can also use the built-in object class for example iterating over the keys with object. keys enumerating over the values with object. values and enumerating over the properties with object. [Music] entries so for your exercise write three for Loops enumerating over the object’s Keys the object’s values and the object’s key value entries so to complete that let’s enumerate over the object’s Keys we can do that with or I can say cons key of object. keys and for the argument I’ll pass in this object that we created then we can CL for log the key so here we get all the keys for object that we enumerate over now we can Loop over all the values so I can say cons value of object. values passing a new item and here we just console log the value so we get the associated values that we passed in as arguments when we first instantiated this object so now let’s enumerate over the key value entries so I can say for con entry of object. entries new item but now we can do console.log we’ll just log out entry so here we see each entry is an array where the value at the zeroth index is the key and the value at the first index is the associated value abstraction is a core Concept in objectoriented programming that involves hiding complex details while exposing only the necessary parts of a class or object to the user this makes the objects in our applications easier to interact with and reduces the impact of changes so let’s consider the programmer Constructor function that we’ve been using and I’ll illustrate the concept of abstraction so we use the function keyword and I use Pascal naming convention to name our Constructor function the parameters are name and preferred language so now we use the this keyword to assign our properties and we will assign our preferred language so now that we’ve assigned those properties let’s create a public method just create a comment just to illustrate that so we use the this keyword to create our public method and I’ll name it write code we assign this to an anonymous function now I’ll use a keyboard shortcut so I can just type out log and so here vs code says log to the console so I can press tab for autoc completion so now I’ll use back ticks because I want to use string interpolation so dollar sign and then curly braces this. name so I’m utilizing this property in our string wres this. prefer language code so this public method is accessible through do notation when we create an instance of this programmer so now to demonstrate a private method so the concept of abstraction refers to using private methods such that the public methods are only those that are absolutely necessary and we want to abstract away the details so I can use the cons keyword I can also use the let keyword so if you recall both the let keyword and the cons keyword are only available within the block that they are defined in right so you can only call it within the block that it’s implemented in so I assign this to an anonymous function so we’ll use our keyboard shortcut again with log and then down arrow and then tab and once again I’ll use back ticks and use interpolation so this.name drinks coffee so now let’s define another public method and now we will utilize this private method that we defined so I’ll use the this keyword and I’ll assign this to an anonymous function and here I will just call our private method so here we see with abstraction we are abstracting away the implementation details which is hidden from the user so to better illustrate this I can create an instance of this programmer so I can say cons programmer I’ll use the newy keyword which calls this Constructor function and we named it programmer so I’ll say name Steven and preferred language is Javascript so now if I do programmer dot here I can see what is accessible through do notation what its public interface is so here I see the name property I see the preferred language and I see the public methods of start day and write code so let’s call write code and I’ll just do shift option and down arrow to create a copy and I’ll try to call drink coffee so here I’m attempting to call this private method and let’s see what happens I’ll save it with command s now I’m going to bring up the terminal so I’m going to do command and J for that so here I’ve already navigated to the directory where this file is located and I name this file 11y abstraction. JS but your file could be named differently and here I’ll just run it in the terminal rather than using qua to better illustrate this so 11 abstraction. JS so here we run it if I scroll up when I called write code this outputs this. name writes preferred language code and so here we see the output is Steven writes JavaScript code so that worked as expected however here we see we try to call this private method and we get a type error that programmer. drink coffee is not a function so we know it’s not accessible and this is what will occur if we try to call a private method so it would throw an exception so now we want to instead use the public method right so only public methods are accessible through dot notation so I’ll clear this with command K and then up arrow and we’ll run it again so now I see I get the expected output when I ran right code however when I called start day this called the private method I defined where we have this. name drinks coffee and here we saw the output of undefined drinks coffee so this means that this.name is currently undefined within this context so if you remember in JavaScript functions are objects and they have their own this context so in this instance this example rather this is referring to the function that is defined in however we want that this keyword to instead reference its enclosing scope so the enclosing programmer such that we can access this. name so order to do that we can use the bind method so I can say bind and I’ll say this which references the current context that’s being implemented in so that Constructor function so now if I run it again let me clear this with command k up arrow and then run and here I see the expected result for this private method call inst start day which is Steven drinks coffee so that is the result of calling this method so to recap in this example we saw that let me close the terminal so you can actually see it right code is a public method that is accessible to any instances of this programmer Constructor function and on the other hand drink coffee is defined as a private method inside the Constructor function and here we use the cons keyword so this method is not accessible from outside this code block so outside the programmer function instead it is meant to be used internally by other methods within the programmer object like start day here which exposes a controlled interaction with drink coffee so this illustrates the concept of abst abration which is utilizing private methods and hiding away the implementation details so some key points on abstraction that I want to discuss two main points one is you just want to show what is necessary in the public interface so in our example here we see that start day that method abstracts away the details of what starting the day entails for a programmer so in this case drinking coffee now the consumer of this programmer Constructor function does not need to know the implementation details they just need to know that they can start the day and call that public method the second point of abstraction is hiding the complexity so methods like drink coffee do not need to be exposed outside of this object as they handle specific functionalities and implementation details that are not relevant to the programmer that is utilizing this Constructor function so this approach helps in maintaining a cleaner interface for the objects making them easier to use and reducing dependencies on the internal implementation details so we can always change those implementation details in the future and minimize the impact of those changes so this leads to better modularity and easier maintenance of our [Music] code so in this exercise we will build upon the grocery item Constructor function that we’ve been using in previous exercises and we will create a grocery list Constructor function so this will help us understand the concept of abstraction which involves hiding the implementation details and exposing only the necessary parts so here is the initial grocery item Constructor function so the grocery list Constructor function should internally maintain an array to store grocery items it should also provide methods to add items display all items and get the total quantity of items so to practice abstraction we will use private methods for operations that should not be exposed directly specifically you will Implement a private method for calculating the total quantity of items so here’s a starting point for the grocery list Constructor function use the function keyword we’ll name it grocery list this doesn’t accept any parameters for the Constructor function then internally we have items which will hold the grocery items I’ll just add a comment private array to store items your task is to complete the grocery list Constructor function by adding the following methods you’ll Implement add item which accepts two parameters for a name and quantity and this adds a new grocery item to the list there is display items which will display all items in the list there is get total quantity which will return the total quantity of all items and we have a private method calculate total quantity to calculate the total quantity of items so by the end of this exercise you will have a better understanding of how to implement abstraction in JavaScript using Constructor functions so now let’s Implement our grocery list Constructor function I’ll scroll down so we have more room so now first let’s Implement our private method to calculate the total quantity of items so you can use the cons keyword and on name this and we’ll name this calculate total quantity we assign this to Anonymous function now we will return this quantity and we utilize the reduce method that’s built in for the array data type so items. reduce so with this we can take all the items in our list and reduce it to one value so here we pass our callback function so the previous value which we can name that total and the current value so I’ll name that it we use our Arrow function syntax so the total plus the item do quantity right so here for our grocery list we have the properties of name and quantity now for the reduce method it also takes an optional second parameter set that to zero and this represents the initial starting value so now I’ve implemented that what a comment here just so we know that it is a private method so now we will Implement our other methods needed to operate on the grocery list array this. add item so an anonymous function picks in the name and a quantity so now let’s create that new object so cons item and then new grocery item says pass in these arguments to create the new object and then we will add it to our items array so now we Implement our display items method assign this to Anonymous function then we can do items and here we can call the buil-in for each method so it would be the item the current item that we are operating on and we simply want to call the display method so the display method we have implemented here and here this console logs the quantity and the name of the item so we can Implement all this on one line so now want to implement get total quantity set this to an anonymous function and we simply will call this private method that we have implemented here so now let’s utilize this grocery list Constructor function so I’ll say cons I’ll name it my list and we’ll use the new keyword then grocery list and this doesn’t accept any arguments so now that we’ve created a list let’s add items to it so my list. add item so I’ll say banana and a quantity of five then just to copy this I’ll do shift option and then down arrow just rename it to be apple and let say the quantity is three let me scroll down so you can see so now let’s call my list do display items so this will go through an output so let’s bring up the terminal so command and J or control and back tick so I’ll do up eror and then I’ll run it so here I see when I call display items this outputs the quantity and the item name for all the items in our list so now I’ll comment this out and I’ll close the terminal just so we can see better now I want to console log I’ll use back tick now I want to find the total quantity of items in our grocery list so total quantity we use interpolation here so my list do get total quantity so we’re calling that public method end it with the semicolon so once again we’ll open up the integrated terminal so command and J or control and J up arrow and we’ll run it again and here we see the total quantity is eight items in our grocery list so some key points on abstraction once again we want to show only what is necessary so only the methods of add item display items and get total quantity are exposed to the user the user does not need to know about how the total quantity is calculated so that is a private method and the second key point is hiding the complexity so if I scroll up again so the calculated total quantity method is private and its functionality is the internal implementation details that should not be exposed closures in JavaScript are a powerful way to achieve encapsulation which is one of the core principles of object ored programming so if you remember our acronym of the four pillars of object programming which is a pi so the A is for abstraction the P is for polymorphism the I is for inheritance and the E is for encapsulation so what is a closure a closure means that an inner function has access to variables declared in its outer function this allows you to hide the internal State and functional of an object exposing only what is necessary to the outside world so this is a technique that enables us to achieve encapsulation so using closures we can create private properties and private methods making JavaScript objects easier to work with so instead of overwhelming the user object with too many public properties and methods you only expose what is absolutely necessary for the object to function properly so let’s go over a simple example to better understand the concept of closures so I use the function keyword and and I’ll name this function example So within it I’ll create a constant named num and I will initialize it to the value of five so now I’m going to create a function within this function so remember in JavaScript functions are objects so I can name this log [Music] num and here I’ll type log and then I can log to the console so I get that auto completion that Visual Studio code provides for me now log out that identifier of num so now I will call or invoke log num so now let’s call example so here we see this inner function has access to the variables declared in its outer scope so it’s outer function which is this constant value so let me bring up the integrated terminal I’ll do that with command J you do this with control J so node and I name this file 12 hyphen private do tab so Auto completes for me so we output that so here when we invoked call this function example we get the expected output of five this is a simple example demonstrating the concept of closures where inner functions have access to variables declared in its outer scope so let’s go through a more complex example in the case when we we return the function so rather than simply defining this function or declaring it rather let’s instead return it so can do return and we’ll delete this so now this function returns a function and so when we call example we want to store the result I’ll name this inner function initialize to that and so now log num is now accessible through inner function right so this is referencing the function that is being returned so now let’s call that inner function in function and we invoke it let’s bring up the integrated terminal again up arrow and we’re running and once again we get the expected result so even though this function which we named example has finished executing inner function still has access to num because of the closure so even after this example or even after the outer function has finished executing the inner function is still able to access all the variables and identifiers declared in its parent scope at the time of Declaration right so you’ll get more practice with this and you’ll become more understandable let’s go over a more complex example and here we will create private properties and methods using closures within a Constructor function
so once again we use the function keyword and I’ll just name this make functions so here if we use the let keyword I’ll name this private num I’ll initialize it to the value of zero so now we’ll create inner function function private increment so this increments the value plus plus so now we have these local values which are not accessible outside of this function and here we will return a JavaScript object and we will define an interface right so methods to use so we’ll have our log num method we’ll Define this with an arrow function so we’ll do log and then tab for that autoc completion this will console log the number now we’ll Define another method increment once again we’ll use an arrow function to Define it curly braces so this will call Private increment here we do log Tab and we’ll just say increment it so now let’s call make function I’ll say cons now we can destructure these values so use curly braces log num and increment make functions and so this is an example of destructuring so we know make functions returns an object and we’ve D structured these two methods so now it’s easier to work with now if we didn’t do destructuring we could name this for example increment object we could really name it anything and through increment object we can access the increment and lognum methods but I prefer the destructuring syntax so did command Z to get back to that so now let’s call log num this will output the value of zero which it was initialize with then we can call increment which will update the value and we will see the console log value of incremented and then we can call log num again so let’s bring up integrated terminal again here I will scroll down we’ll clear it with command K up arrow and we run it again so here we see the initial value of private num is zero we incremented the value and the updated value is one so this shows an example of closures as this make functions has finished executing but here this JavaScript object and the methods defined within it still have access to these identifiers or the the variable is declared in its parent scope and this helped us achieve encapsulation because we only expose log num and the increment method and we’re not exposing the in implementation details or the private num property so let’s clear this out we’ll go through another example so using closures in a Constructor function so we’ll go back and we’ll use our example for the programmer Constructor function the parameters are name and preferred language so I’ll just write some comments just so it’s easy for us to identify what we’re doing so we’ll specify a private property so we’re not going to use the this keyword so it’s not accessible through do notation so I’ll use the let keyword instead and we’ll assign this to the value of name now an example of a public property which will be accessible through notation so this do preferred language assign to that parameter of preferred language so now let’s define a public method we use the this keyword say write code assign this to an anonymous function let’s do log and then tab for the auto completion we use back ticks and we can say code in this preferred language now an example of our private method Again Play Let drink coffee assign to an anonymous function here we will log it again so log to console I’ll just say gulp dot dot dot now we’ll say a public method that uses a closure so this. start day assign this to Anonymous function and we just call drink coffee so we are hiding those implementation details of this so let’s actually instantiate a new programmer so we’ll say const programmer we use the new keyword and the name of our Constructor function we’s say Alis and the language is Javascript and this with the semic colum now programmer. write code and we’ll say programmer. start day right so this repetition is really good to help you get used to the syntax as well as get a better understanding of the terminology that we use in programming let’s scroll down open up the integrated terminal up arrow and run so here we see code and JavaScript and go so in these examples let’s close this and we’ll look over our implementation of this Constructor function so private name let’s actually use it so can use private name right so let’s run it again to make sure that we’re actually utilizing our private property so here we see Alis codes in JavaScript and just sculp so private name and drink coffee are private because they are defined with the let keyword and not exposed via the this keyword so considering public properties and methods preferred language and write code are public because they are defined with the dis keyword and can be accessed outside the function and through dot notation once we create an instance of this Constructor functions programmer so using closures so the start Bay method demonstrates a closure is a public method that can access the private drink coffee method because of the closure it can access uh variables and identifiers is declared in its outer scope so let’s consider closures versus scope so scope is the context in which variables and expressions are visible or can be referenced if a variable is not in the current scope it is unavailable for use now for closures these are functions that capture and reference external variables so when I say external variables this refers to variables which are not defined locally in the function but these variables are accessible because they exist in the outer environment the function defined in the closure remembers the environment in which it was created at the time of function declaration this is why drink coffee this method remains accessible only within functions defined in the same scope so only within the Constructor function so closures are a fundamental and Powerful aspect of JavaScript allowing for more secure and modular code by protecting and encapsulating behavior within objects so we’ covered a lot of new terminology in this lesson I’m not expecting you to remember and nor all of it immediately and we’re going to get more practice and more exposure to these Concepts throughout the course so it will make more sense the main takeaway that I want you to get from this lesson is that a closure means that inner function has access to variables declared in its outer function what are closures so closures are inner functions that are able to access variables defined in its outer function so in other words closure functions can access variables from their outer scope even after the outer function has finished executing now you would utilize closures in order to achieve encapsulation and to hide private variables or private properties so now for your exercise the objective is for you to understand and Implement closures to create private properties and methods within a Constructor function so your task is to create a bank account Constructor function that can manage a user’s account balance so the balance should be private and the Constructor should provide public methods to deposit money withdraw money and check the balance so now to go over the instructions step one you want to define the bank account Constructor function now it should have a private variable balance to store the account balance it should have a private method to validate the amount being deposited or withdrawn so this private method will validate and ensure that the value that you’re passing as an argument is of the number data type and that the amount stored in the balance is greater than the amount being withdrawn as well as the money that you’re depositing is a positive number so it should have public methods to deposit money withdraw money and check the balance so step two you want to implement the following public methods the first is deposit which accepts the parameter of the amount to deposit so this adds the specified amount to the balance if it is valid right you’re utilizing that private method to validate the argument the second method or second public method is withdraw which accepts the parameter of the amount and this subtracts the specified amount from the balance if it’s valid and there are sufficient funds now the third public method is get balance which simply Returns the current balance so pause the video and attempt to implement this Constructor function for the bank account so now you’ve attempted to implement that we’ll go ahead and write the code for that so we use the function keyword then name of it is bank account now for the parameter I’ll specify initial balance now I’ll use this as a private property so it’s not accessible through notation you can only access it through the public interface or the public methods this helps us achieve encapsulation so we’re setting that to the initial balance and I’ll add a variable just to better describe what I’m doing so private variable to store balance okay now I want to implement the private method to validate the amount so this amount could be what is being used to either deposit money or to withdraw money so cons I’ll say is valid amount the anonymous function parameter being amount so return and I’ll use the type of operator CU I want to ensure that the amount is of the number data type so and we will check that the amount is greater than zero because we can’t deposit a negative number and we don’t want to withdraw a negative number so we can utilize this helper method in our public methods that we’re going to implement so I’ll just say public method to deposit money so we use the this keyword to create a public method within our Constructor function we name a deposit and we assign this to an anonymous function with the amount being the parameter now we’re going to use utilize our private method so if is valid amount for the amount then I’ll do curly braces so in the case when the amount being deposited is a number data type and is a positive number then we want to perform that update so we’ll use our shorthand syntax to update the balance in the bank account and we will log it out so I’ll say log down arrow and then tab I’ll use back ticks so deposited now the colon now we’re using interpolation so I’ll do a dollar sign and the curly braces and the amount now because I’m doing US dollars I want to use the dollar sign in the actual output so I’m going to add another dollar sign before just so um the correct symbol shows up when we output it to the console so now else in the case when it’s not a valid amount so do log then tab and and then I’ll say invalid deposit amount so I’m informing the user on that so we’ implemented this I can end that with the semicon now want to implement the public method I’ll scroll up so you can actually see better so public method to withdraw money so now we’ll do this do withdraw we assign this to an anonymous function now once again um we’re utilizing our helper method so if is valid amount we ensuring that that is a number data type and a positive number and if the amount that we’re trying to withdraw is less than equal to the balance then we can actually perform that so we use shorthand syntax to update the balance so minus equals and we will log that to the user to inform that this has been successfully performed back ticks with Drew interpolation the amount and we want the dollar sign show up so we’ll add that there else we’ll log and then tab insufficient FS now in the case when it is not a valid amount so in the case when the amount that you passed as an argument is either not the number not of the number data type or is a negative value then we want to Output a message for that case so I’ll say invalid withdraw amount okay so we implemented that we have one more public method which is to get the current balance so once again we use this keyword get balance Anonymous function and then we will simply return the balance so we’re just returning this private property that we set here so now we’ve implemented this I’ll scroll up so we can actually utilize it so now let’s instantiate an instance of this and call this Constructor function so I use the con keyword I’ll name the identifier my account and we assign this to new bank account now for the initial value I’ll specify 100 as the initial balance so now I can do my account. deposit not deposit 50 now let’s do my account. withdraw and I’ll withdraw 30 and we going do console.log and I’ll say my account. getet balance so let’s call it so now let’s open up our integrated terminal I could do that with command and J or control andj now I’ll do up arrow and I’ll run this so here we see the correct console logging where we deposited $50 and then we withdrew $3 and because we started with the initial balance of 100 we get the expected output of 120 so let’s close this integrated terminal and scroll back to the code that we wrote for this exercise so an explanation of it we have private properties and private methods here our private property of the balance of the bank account and the private method which is the is valid amount helper method so the balance variable and the is valid amount function are private because they are not exposed via the this keyword right we’re using the let keyword and the cons keyword so these are accessible within the block that it is defined in so accessible within the Constructor function now we have public methods with deposit withdraw and get balance and they’re accessible and public methods because they utilize the this keyword they could be accessed outside of the function through dot notation now for using closures the public methods demonstrate closures in the sense that they can access the private balance variable and the is valid amount function because they are defined within the same scope right so closures are inner functions that can access identifiers or variables in its outer function so some key points on closures first is it helps us achieve encapsulation where we hide internal State and functionality exposing only what is necessary another key point is scope so this is the context in which variables and expressions are visible or can be referenced and to recap on closures these are functions that can access variables from their outer scope even after the outer function has finished executing so by completing an attempting exercise you have more experience with closures and have a better understanding of how to create private properties and method methods to encapsulate the internal State and functionality of objects Getters and sets are special methods that provide you with a way to get and set the properties of an object this encapsulation technique allows you to control how important values are accessed and modified in your objects it’s often used to ensure that data encapsulation and validation rules are followed here’s how you can incorporate Getters and Setters into the programmer Constructor function using object define properties so here we have this private property private name and we cannot access it through do notation so in order to access that value you can do object. define properties now if I hover my mouse over that the first parameter is the object where we want to add or modify properties so I’ll use the this keyword which means this current object or this programmer object and for the second parameter I will specify an object again this with a semicolon and here we’ll Define the name of the property so name it name and then def find an object and here we can use the special keyword for get and we’ll set it to an anonymous function and this will simply return the private name so now if I actually want to use this property I’ve instantiated programmer object and do log tab I can say programmer. name so rather than having to call doget I simply can access it through a property and that will call the get method let’s run this in the integrated terminal so command J or control J and I name this file 13 Getters and Setters so do tab the auto complete and then I’ll run it and here I get the name of the programmer which I have access through that get method that we defined right through that name property which we defined here now we can also set the value we use the keyword for set and we’ll set this to an anonymous function the parameter will be the new name that we wanted to set now with Setters we can Implement validation rules to ensure that the value that we are setting is appropriate so I can check and make sure that the new name is not falsy which means that the new name is not an empty string null so in the case when value that I was setting is falsy I can log to the console and I can say the name cannot be empty and then we will use the return keyword to stop the execution otherwise we will set the private name so here say new name now let’s utilize this Setter method now we would do this through the name property I scroll down here if I want to set the name I can say programmer. name and I’ll set it to my name Steven now here I’ll copy this and here we see the name is changed so open up the integrated terminal again up arrow and we run it so here we see I successfully changed the name to be Steven we’re able to accomplish this because of the setter method now let’s check and make sure that our validation rules apply so let’s say instead of assigning this to my name Steven let’s say if it was an empty string integrated terminal clear this out and run it again here we see this console log statement saying the name cannot be empty and then when we log the name again we see it continues to be Alice which means that our validation rules were applied Getters and Setters the name property has a getter and Setter defined and the getter simply Returns the current value of the private name this private property while the setter allows you to validate the new name before signing it to private name so this is an example of encapsulation utilizing gets of Setters also known as accessors and mutators and this structure ensures that the internal St of the object in this case the private name can only be changed in controlled ways increasing data integrity and interaction safety using Getters and Setters not only encapsulates the internal state but also allows for additional logic to be implemented when getting or setting a property such as validation or logging which enhances the functionality and robustness of your code in this section we covered the fundamentals of objectoriented programming beginning with a definition of oop and an exploration of its four core pillars we covered essential Concepts and techniques including object literals Factory functions and Constructor functions which are foundational in understanding how objects are created and utilized in JavaScript we also discuss the Constructor property which links an object back to its Constructor function and examine how functions themselves can be treated as objects in JavaScript this leads to a deeper understanding of javascript’s flexible approach to oop important distinctions between value and reference types were highlighted clarifying how JavaScript handles data storage and manipulation which is crucial for Effective memory management and performance further we explore Dynamic aspects of objects such as adding removing and enumerating properties providing practical skills for manipulating object properties in real time the concept of abstraction was introduced along with practical implementations of private properties and methods which enhance encapsulation and data hiding in JavaScript finally use of Getters and Setters were discussed illustrating how these can be employed to control access to an object’s properties ensuring data integrity and [Music] encapsulation this section focuses on inheritance a fundamental Concept in object ored programming that allows one object to inherit the properties and methods of another this mechanism is key for reusing code efficiently and effectively I’ll introduce some terms that are critical to understanding different aspects of inheritance so the terms to First consider are Base Class super class and parent class so these are all synonymous and they all mean the same thing and these terms refer to the class whose features are inherited by other classes so now consider the terms derive class subass and child class so these three terms are all synonymous as well and these are classes that inherit properties and methods from the base class this relationship is often referred to as an is a relationship indicating that the derived class is a specialized form of the base class so I don’t expect you to memorize these right away I wanted to expose you to these terms so you understand what they are and we’ll see practical examples throughout this course so we can also differentiate between two types of inheritance the first being classical inheritance so this is found in class-based languages where inheritance is defined through classes and these include program languages like C or Java now the second type of inheritance is prototypical inheritance this is specific to JavaScript and this type of inheritance does not involve classes instead JavaScript uses prototypes this refers to objects that other objects can inherit properties and methods from it’s important to note that in JavaScript the traditional concept of classes is implemented differently while es6 which stands for modern JavaScript introduce class syntax it is syntactic sugar over JavaScript existing prototypical inheritance model understanding this helps clarify how JavaScript handles inheritance and sets the stage for using these Concepts to structure and reuse code [Music] effectively what is inheritance and why is it important inheritance is a concept in programming where one object can inherit properties and methods from from another object in JavaScript this is done through prototypical inheritance also called prototypal inheritance it’s important because it allows for code reuse making programs more efficient and easier to manage inheritance is one of the four pillars of objectoriented programming along with encapsulation abstraction and polymorphism what type of inheritance model does JavaScript use prototypical inheritance or classical inheritance JavaScript uses the prototypical inheritance model this means objects can inherit properties and methods directly from other objects rather than from classes as in classical inheritance what do these three terms refer to Base Class super class and parent class in JavaScript the term is Base Class super class and parent class all refer to the same concept the class from which another class inherits properties and methods these terms are often used interchangeably to describe the original class that provides functionality to a derived or child class what do these three terms refer to derived class subass and child class in JavaScript the terms derive class subclass and CH class all refer to the same concept a class that inherits properties and methods from another class with that other class being the parent class these terms are often used interchangeably to describe the new class that extends the functionality of the original [Music] class in programming enhancing an object’s functionality is a common task ask I will initialize some objects I’ll say let user and assign this so it’s just an empty object literal then I’ll create admin and I’ll create a guest so now consider these three objects that we’ve created now if we were to add properties and methods to this user object literal and we also have the admin and guest objects it is beneficial to reuse what we have in the user object as they’re going to have the same properties and methods now the admin and guest objects are more specific versions of the user object now both the admin and guest are users of the website so we can utilize prototypal inheritance to accomplish this in JavaScript objects possess a special hidden property prototype that is either null or references another object this reference object is also called a prototype when you see the term prototype think of it as interchangeable with parent similar to a parent class from which properties and methods are inherited so I’ll add some properties and methods to this user object to demonstrate this if this user object were to have the property of name I’ll set that to my name then the property of surname so I’ll set it to my last name email which is stepen Stephen codec craft.com is active say true now I can find some Getters and Setters so I’ll use the set keyword and I’ll set it to be full name the parameter will be value so now we’ll perform destructuring so I’ll use square brackets and I’ll say this.name and this. surname assigned to Value dos split on whitespace so with the set keyword I’ll be able to use full name through notation and assign it to value so for example it would look like user. full name is assigned to let’s just say Bruce Wayne for example so here is how we would utilize the setter now we call the split method on the value that is passed in which is this string and we split it on whites space so now we are destructuring it because when we call split this stores these strings into an array so Bruce would be at the zeroth index and Wayne would be at the first index and so that is how we set it here and this is a clean syntactic sugar that we can use to do it all on one line so now we Define a getter so I’ll say get full name and then I can show us return I’ll use back ticks so I can use interpolation this. name space this do surname and I’ll end this with semicon so I need add a comma here and then a comma after this so now I’ll add two more methods for log in and log out so I can console.log I’ll use a short hand so log and then back tick this. full name right so I’m using the setter here logged in then another comma and then log out to log turn then tab back to this. full name log down so here we see we have implemented properties the Setters and getter and two methods now this same functionality is also required in the admin object and the guest object now we don’t want to duplicate our code and have to copy and paste it so there is a cleaner way that we can do this utilizing inheritance and specifically prototypical inheritance or prototypal inheritance so here rather than having to copy and paste it because admin is a user of the website it satisfies that condition we can use a special property known as Proto which stands for Prototype so it’s two underscores then Proto two more underscores that will be the key for this property and we set this to user so what we’re doing here is we’re saying that the parent of this object is the user object so it’s going to inherit these properties and methods so this enables us to inherit all this functionality without having to duplicate all the code so because admin is a more specific version it is a derived class it’s more specialized than the user object it’s more specific so I can say is admin is true so here we are inheriting all the functionality of that user object and we are also extending it so I can also add a custom method manage users which is just specific to the admin object so here I would do log and then tab back ticks so here we can utilize what we inherited from the user object so this. full name is managing users now we can also utilize prototypical or prototypal inheritance in the guest object so once again we use Proto and the user so we can say is guest it’s true and I’ll add a custom method here so say browse content log and I’ll say this. full name his browsing conare notice how we are not duplicating properties and methods in our objects if you attempt to use a property not Define an object JavaScript automatically retrieves it from the Prototype this concept is known as prototypal inheritance the Prototype property is internal and hidden but it can be set in various ways one of which is using the special Proto property that we were using here so if we didn’t set it in the definition of this object literal let’s say if I were to remove this for example then we can also set it through dot notation so I can do admin Proto sign it a user so that would work as well so I’m going to do command Z undo this so if the user object here has many useful properties and methods they become automatically available in their derived objects so admin and in guest and these properties that inherits is known as inherited properties so the Prototype chain can extend even further so let’s say if we had a even more specialized object let me Define that here I can say let super admin which is an even more specific object with enhanced Privileges and enhanced functionality I can say the Proto right so it’s parent object is admin so it’s referencing as a parent this admin object and this prototype is set to the user object so super admin will inherit all of the properties and methods defined here in the user object and it will inherit the properties and the method of the admin object so let’s add some more specialized functionality I can say is super admin is true and I’ll add a method I’ll say manage admins I’ll do log and then tab this. full name is managing admit full so there are some limitations to prototypical or prototypal inheritance the first being is that prototype references cannot form a circular chain otherwise JavaScript throws an error for example setting the user Proto object to be super admin would cause a circular reference now the second limitation is that the Proto value can only be an object or null other types are IGN Ed an object may not inherit from two other objects simultaneously the value of the this keyword in methods refers to the current object even if the method is inherited so here we’re using the this keyword it’s referring to this current object the admin it’s not referring to the user object so setting a property in an inherited object modifies only that object State and does not affect the base object state so to demonstrate that by scroll down here let’s say if I already do admin. full name and I set this to Bruce Wayne now say if I log this out I will log the admin. name and I will log out the user. full name I’ll bring up the integrated terminal I go back and I change into prototypes directory I’ll do node two I’ll do tab to autocomplete it if I run it here I see the admin’s name is Bruce Wayne and by setting it it did not change its parent it did not change its prototype right so it only affected the current object so when I log out user it logs out Steven Garcia which is the value that we set when we first created the object literal so now consider the four in Loop so we can use the for in Loop to iterate over both the object’s explicitly implemented properties and inherited properties of an object so here if I just comment this out I will say for let key in admin I can do log and here I would just log out the key once again when we bring up the integrated terminal I’ll clear this command K up arrow and run it so here we see is admin we scroll to the admin implementation here we see that property being defined we see manage users which is that specialized method we implemented and we see all of the properties and methods implemented by its parent by its prototype in the user object now one thing to differentiate here we comment this out if we were to do or utilize object. Keys object. values or object. entries this will return only the explicitly implemented properties for that object it will not output the inherited Properties or methods so far to do log and then I do object. keys of the admin let’s bring up the integrated terminal up Arrow run it so here we see is admin that property that we explicitly Define and that specialized method manage users so this will not output any of the inherited properties and methods of the Prototype so for this video we were using the Proto property which is a geter in Setter for the internal prototype property however in modern JavaScript we prefer to use object. getet prototype of and object. set prototype of so a summary of what we’ covered so far in JavaScript all objects have a hidden prototype property that is either another object or null if an object or method is not found in an object Java scpt looks for it in the Prototype write and delete operations directly affect the object itself and not the Prototype so by changing that in the derived class it will not impact the parent object so by changing that in the derived object it will not impact the parent object and the Forin Loop iterates both over explicitly defined properties and inherited properties of an object while other key value getting methods only operate on the object itself so let’s go over another example in JavaScript we know that inheritance is achieved using prototypes which are essentially objects that other objects can use as a template and we know that this process is called prototypal inheritance so for another example let’s create an object that encapsulates common behavior and properties that are shared amongst all programmers so I’ll use the cons keyword and I’ll name it programmer prototype so be object literal will Define a method so an anonymous function will log it back tick say writing code in this dot preferred language comma will to find another method drink coffee s Anonymous function and we will log drinking coffee now we end this object literal with a semicolon so now we can create a Constructor function in then we’ll use this base object as its prototype so as the parent object so we’ll use the function keyword and we’ll name it programmer the two parameters are the name and the preferred language so say let private name is assigned the name so this is a private property so I can say object. define properties the first argument will be this for the current object and we’ll pass an object as the second argument so we’ll specify the property to be Nam and it will have a getter and Setter so Define the get Anonymous function and this just Returns the private name comma then set the new name private name is assigned to the new name now we’ll also set the preferred language let’s just do that here this do preferred language is set to the preferred language now at the bottom we want to inherit the common Behavior you scroll up defined in the parent object so I can say object dot set prototype of so the first argument will be this for the current object and the second argument will be the object which will be the Prototype so this case is the programmer prototype so let’s instantiate this I’ll say cons and JS programmer equal to new programmer so the name will be Alice and the preferred language is Javascript so to better explain what we just implemented we Define a programmer Constructor function that has a private property named private name we Define Getters and Setters so we can access this private name do the property of name so this demonstrates encapsulation so we are hiding the inner details of this object and we also set the Prototype with the method set prototype of so this will allow all instances of programmer to utilize the methods built into its parent object so all instances when we call a programmer we have the right code method and the drink coffee method so now let’s verify that the inheritance is working correctly by calling the methods on this JS programmer object so we can do JS programmer. write code you can try JS programmer. drink coffee now we’ll log it out so be JS programmer logging out the name so here we are utilizing this getter to get the private name now we’ll use the setter and I’ll set this to my name Steven and we will log out the updated value so JS programmer. name so let’s scroll up and open up the integrated terminal with command J so up arrow and we run it so here we see the result of the write code method says writing code in JavaScript if I scroll up this functionality is in the Prototype here we see right code in preferred language now when we called the drink coffee method this outputed the expected string drinking coffee now if I scroll back down we outputed the name so we got Alice we updated the name and log that out and we saw the name of Steven so this example showcases how to effectively use prototypes to implement inheritance and Java Script allowing for shared behavior and properties while maintaining encapsulation of private data so so by leveraging prototypes the programmer object can be extended to create various types of programmers with minimal code [Music] duplication what is the Proto property in JavaScript the protor property is a reference to the Prototype of an object it allows objects to inherit properties and methods from another object this property is used to set for access the Prototype directly but it is considered outdated instead modern JavaScript uses object. get prototype of and object. set prototype of for these tasks in JavaScript multi-level inheritance allows objects to inherit properties and methods from multiple levels of prototypes so consider this simple example if I just declare an array and I assign this to an empty array so when my array is created it is not just an instance of an array but also part of a larger inheritance hierarchy so my array is an instance of array and array. prototype also referred to as array base provides methods and properties common to all arrays now object. prototype also referred to as object base is the prototype for array base it provides methods and properties that are inherited by all objects in JavaScript including arrays this setup forms a multi-level inheritance chain where my array inherits from array. prototype and array. prototype inherits from object. prototype this is how the inheritance looks in a structured form so the base is object. prototype also known as object base then array. prototype extends that also known as array base and then our instance of the my array so some key points objects created by a specific Constructor like array will share the same prototype in this case array. prototype this multi-level inheritance allows objects like my array to access properties and methods defined in object. Prototype giving JavaScript its Dynamic and flexible nature understanding this inheritance structure helps in recognizing how methods like two string or has owned property are available to your array even though they are not directly defined within the array Constructor or on the array instance itself this concept is fundamental to mastering javascripts prototype based inheritance and helps in designing more efficient and robust applications [Music] so moving forward in this course we’ll be using the live server extension in vs code in order to improve our productivity and reduce our need to run our code in the integrated terminal so click on the icon for the extensions Marketplace and search for live server Swiss extension allows us to have hot reloading where it will run our JavaScript code in a web browser and when we make a change in our JavaScript code it will automatically update and we can see those changes without having to constantly run it in the terminal so now that you have that installed I’ll close this back to our folders I’ll create a directory so you can click on this icon and I’ll name it underscore practice you can name it whichever you prefer now within it I’ll create a new file and I’ll name it index.html now I’ll be creating a course on HTML and CSS so no need to be an expert in those Technologies we just need this file in order to open up a web page with live server also create a file named index.js and here we will place our jscript code for our lessons so back to the HTML file we need to create the Border plate for an HTML document so visual studio code will generate this for us simply type in an exclamation point and here we see emit abbreviation so just do Tab and here vs code generate this for us so now we want to reference our Javascript file so within the body element or body tags type in script and then type text SL JavaScript now we will reference our index.js file here so we’ll do source. SL index.js as it’s in the same directory then we will have a closing tag and that’s it so now now we’ll open up our Command pallet so that’s command shift and P or control shift and P type in Live server open with live server so this will open our index.html in our web browser now because we don’t have any HTML written between the body it’s just a blank web page for now so let me close the sidebar with command B and I will resize this so now our JavaScript will be running in the JavaScript console we can see that in the dev tools also I suggest that you use Google Chrome unless you are more comfortable with Microsoft Edge or Firefox so now to open up the Google Dev tools the keyboard shortcut is command option and J you can also right click and then click on inspect so here in order to get this to open in a new window click on these three dots and here when it says doc side you want to click the left most icon so this will open the dev Tools in its own window now to see our JavaScript code you want to click on console so now we can click on this settings icon to hide that now in order to see and execute our javascri code Type in log right and then we’ll do Tab and then hello world then save it and now we see it reflected on the right side console so we no longer have to constantly run it in integrated terminal so here I’ll do command and plus so we can see the text more easily so in JavaScript we know that we can define an object like this by creating an object literal say the name and the value of Steven we can end this with a semicolon and we can log out this object with person and here we see output it on the right hand console now let’s iterate through this using a Forin Loop so I can do four let key in person then log and tab and just log out that key Val value so here we see the key of name was outputed now notice how only the properties defined directly in this person object are displayed similarly if we use object. keys so let’s log that out object. keys and then the person object we output that we see the value of name so this only shows the properties defined at the object’s own level so the properties that inherited from object. prototype also refer to to as object. base aren’t displayed because of specific attributes attached to those properties so these attributes can control whether properties are innumerable rable and configurable so in other words these attributes determine whether the property will be outputed when iterating over it such as with a for end Loop or if using object. keys object. values or object. entries so let’s see this in action I’ll clear this out and we’ll examine the prop descriptor for the two string method which this person object inherits from object base so I’ll clear this out as well and I will expand this so we can see it more easily so we’ll say let object base assigned to object. getet prototype of the person object so we’re getting the parent object of this person object now we will do property descriptor this is object. getet own property descriptor of the object base so that parent object and the two string method which is defined in its parent so now we’ll do log tab property descriptor and we will see those attributes that determine whether the two string method will be shown when we enumerate through person object so let’s save this and we’ll see the result in our console let’s expand this so we see the attributes of configurable inumerable what the value is and writable so the one we are concerned about is the innumerable and we see the value set to false so when the innumerable attribute is set to false this prevents the two string method from appearing in the output of a for in Loop and methods like object. keys so you can also Define or modify these attributes so configurable inumerable and writable for properties in our own objects so for instance if we wanted to make the name property here non- enumerable you could do this so we can do object. Define property now the name of the object and the name of the property and we can pass it an object we can Define these attributes so we can say writable is false now innumerable is false so now it won’t show up when we do a for in Loop and configurable is true so let’s comment this out for now we’ll expand this so after this change the name property will no longer appear in a 4N Loop or object. keys so let’s just demonstrate that let key in the person object then we can log all the keys that are innumerable let me resize this and we can clear this out by clicking this icon you can save it and here we see there are no innumerable keys so no innumerable properties in this person object because we Define this here for the name property so by default when properties are created directly on an object they are writable inumerable and configurable attributes are set to true this allows properties to be modified enumerated and reconfigured unless explicitly changed understanding these property attributes and their implications helps in managing how data and objects is accessed and manipulated providing greater control over object behavior in JavaScript [Music] applications what are the property descriptors or attributes in JavaScript that determine whether a property can be accessed modified or iterated over in JavaScript property descriptors or attributes that determine whether a property can be accessed modified or iterated over are innumerable writable and configurable so for inumerable if true the property will appear during four in loops and object. keys for writable if true the property’s value can be changed for configurable if true the property descript can be changed and the property can be [Music] deleted in JavaScript every object has a prototype except for the root object which is at the top of the Prototype chain the Prototype acts as a template or parent from which the object inherits methods and properties accessing an object’s prototype the recommended method to get the Prototype of an object is by using object. getet prototype of this function Returns the Prototype or the parent of the specified object Constructors and their prototypes in JavaScript Constructors are special functions used to create instances of objects since functions in JavaScript are objects themselves they too have properties one of which is the Prototype property this property is not the Prototype of the Constructor itself but rather the object that will be used as the Prototype for all instances created with that Constructor so for example if I create a Constructor function with the function keyword and if I name it circle now the code within the code block so that will be used for instantiating a new Circle object so now if I log this out we know that functions are objects in JavaScript so I can do Circle and it has a property of prototype so if we log that out here we see this empty object we can expand it this object is used as the parent for all objects created with new Circle close this out and I can comment this out creating objects and their prototype links when you create a new object its prototype or its parent is set to the Prototype of its Constructor function so this is Illustrated with say if I create an object literal and I assign this to curly braces so this is syntactic sugar for let object equal to new object so the Prototype of obj or object can be referred to using using the Proto property which is an accessor property that exposes the internal prototype linkage so we’ll just log that out log and then tab see the object and then two underscores before and after Proto so here we outputed that we can expand it so this would be the same as doing say if we do log object. prototype so we get the same output close this me expand it so now if we were to expand it we can expand the get and here we see the internal prototype is object so understanding how prototypes and Constructors work in JavaScript is crucial for effectively leveraging languages object oriented capabilities by grasping these Concepts developers can better manage and utilize object inheritance in their programs and reduce code [Music] duplication does every object have a prototype in other words does every object have a parent object every object has a prototype or a parent object except for the root object which is at the top of the Prototype chain so an object will inherit the properties of methods from its prototype or parent object do Constructor functions have their own prototype yes Constructor functions have their own prototype in JavaScript functions are objects so they have their own prototype property which is used to assign properties and methods to instances created by the Constructor function optimizing memory usage with prototypes in JavaScript in Practical applications especially those involving numerous object instances it’s important to manage memory efficiently if each object instance were to maintain its own copies of methods this would lead to significant memory overhead when dealing with thousands of objects how JavaScript handles method access to address this JavaScript utilizes prototype based inheritance when a method is called an object the JavaScript engine first checks if the method exists on the object itself if the method is not found the engine then looks up the Prototype chain of the object utilizing the Prototype property each Constructor function in JavaScript has a prototype property which is shared by all instances of the Constructor this shared prototype is crucial for memory efficiency so Dem for example this we just create a Constructor function name programmer the two parameters being named and preferred language then we use the this keyword to assign it and the preferred language so now methods added to the Prototype are shared across all instances so I will expand this just so we can see it more easily we can do programmer so that Constructor function. prototype write code so we can assign this to an anonymous function and here we do log and back tick so we can use interpolation this. name writes code in this. preferred language end this with a semiconon we could also override the two string method for all instances so we can do programmer. prototype do two string assign this to an anonymous function say programmer this.name comma language this. preferred language and that with a sumon so now let’s create an instance of this programmer so I can say const JS programmer new PR programmer I’ll say Alice and the language is Javascript now let’s just call JS programmer. write code now we save it and here in the console we see the expected output so the advantages of using prototypes let me expand this again so we can see the code the First Advantage is memory efficiency since methods defined on the Prototype are shared there is only one copy of each method in memory memory regardless of the number of instances this is especially beneficial in applications where many instances of a class are created as it saves a significant amount of memory so for example if we were going to create many programmer objects they would all share these same methods so right code and this implementation of the two string method so the second Advantage is flexibility javascript’s Dynamic nature allows you to add or modify methods on the Prototype at any time modifications to the Prototype are reflected across all instances immediately which can be particularly useful for updating functionality at runtime and the third Advantage is overriding methods so you can easily override inherited methods by defining new implementations on the prototype for example the two string method for programmer has been overwritten to provide more specific information about each programmer instance managing instance and prototype members so first consider instance members these are defined within the Constructor function and these are unique to each instance such as the name and preferred language in the programmer Constructor these properties are set per individual object and manage data that varies from one instance to another now consider prototype members these are defined on the constructor’s Prototype and these members are shared across all instances like the right code and two string Methods this setup is optimal for methods that perform generic actions applicable to all instances by strategically using prototypes to share methods among instances you can enhance your job JavaScript applications both in terms of performance and maintainability this approach ensures efficient memory usage while maintaining the flexibility to adapt the shared behavior of objects how does using prototype based inheritance in JavaScript help in managing memory efficiently when dealing with numerous object instances using prototype-based inheritance in JavaScript helps manage memory efficiently because methods defined on the Prototype are shared among all instances of an object instead of each instance having its own copy of the method there’s only one copy stored in memory this significantly reduces memory usage especially when creating thousands of instances as all instances refer to the same method on the Prototype what are the advantages of defining a method on a constructor’s prototype as opposed to defining them within the Constructor function itself defining a method on a constructor’s prototype in JavaScript has several advantages one being memory efficiency methods on the Prototype are shared by all instances so only one copy of each method exists in memory saving space when creating many instances a second Advantage is consistency changes to a prototype method are immediately reflected in all instances making it easy to update functionality across multiple objects the third Advantage is performance shared methods reduce the memory overhead and can lead to better performance as there is no need to duplicate methods for each instance understanding prototype Dynamics in JavaScript so in JavaScript changes to a constructor’s prototype affect all instances regardless of whether they’re created before or after the changes this Behavior highlights javascript’s use of object references for prototypes consider the programmer Constructor function so just create this takes the name and preferred language as parameters we’ll set these properties so now let’s instantiate it I’ll set cons I’ll just call this programmer new programmer with the name of stepen in the language of JavaScript so now let’s add a new method to the programmer prototype so we do programmer prototype write code sending this to an anonymous function console.log say this.name writes code in this. preferred language end that with the semic and let me expand this so we can see the full method so even though programmer this instance was created before the right code method was added to the Prototype this instance can still access the right code method so let’s do that do programmer. write code we can save that and here in the console we see the console log statement Steven writes code in JavaScript so enumerating object properties so using a Forin Loop you can enumerate over all properties of an object including those on the Prototype so here we can do for let key in programmer we do log while the keys and let’s comment this out for now can save that now here we have enumerated over the properties so we have the name the preferred language and the method right code So based on the JavaScript documentation properties defined directly on the object are referred to as own properties while those inherited from the Prototype are called prototype properties so checking for own properties you can use the has owned property method me to determine if a property is an own method of the object so we’ll see an example of that do log programmer do has own property we’ll say the name output that and here we see the output of true let me comment this out we’ll clear it just so it’s easier to see so that the name property is an own method meaning that it was defined within the Constructor function so let’s see another example I’ll do shift option and down arrow to copy that and I’ll specify right code so this is the name of the method or the member that was defined on the Prototype here when we save this we get the value of false indicating that this is a prototype property so this method has own property helps distinguish between properties that are part of the object itself and those inherited from the Prototype understanding the distinction between own and prototype properties is crucial for working effectively with object or features in JavaScript this this lesson demonstrates the dynamic nature of prototypes and their practical implications providing a deeper understanding of how JavaScript handles object properties and inheritance how does adding a new method to a constructor’s prototype affect existing instances of that Constructor in JavaScript adding a new method to a constructor’s prototype in JavaScript makes that method available to all existing instances of that Constructor as well as any new instances created afterward this is because instances reference the prototype for methods so they automatically have access to any new methods added to the Prototype even if they were created before the method was added what is the difference between owned properties and prototype properties in JavaScript and how can you check if a property is an owned property of an object in JavaScript only properties are those defined directly on an object while prototype properties are inherited from the object’s prototype to check if a property is an own property of an object you can use the has owned property method if this returns true the property is an owned property if it returns false the property is inherited from the Prototype or from its parent while JavaScript allows you to extend the functionality built-in prototypes such as adding a shuffle method to array. prototype it is generally advisable to avoid doing so so here’s an example of what it might look like do array. prototype and we extend it by adding a shuffle method assigning this to Anonymous function and here I just add a comment this would be implementation of the shuffle so then when we create a new array assign this to an empty array then I’ll be able to call array. Shuffle so here let open up the tools let’s just log something out I’ll just do log and I’ll say Shuffle I save that it reach the output of Shuffle so this approach may seem convenient because we can add our own custom methods to builtin data types in JavaScript however it carries significant risk so there is a potential for Conflict for example Library conflicts if you modify a built-in prototype you risk conflicts with thirdparty libraries that might rely on the default behaviors of these objects different implementations of the same method can lead to inconsistent Behavior cross parts of your application as a best practice do not modify objects that you do not own this helps with maintainability and compatibility modifying objects that are globally accessible like built-in prototypes can make your code harder to manage and predict it may also break compatibility with future versions of Javas script or interfere with enhancements in third party libraries so for an alternative approach instead of modifying built-in prototypes consider a safer alternative you can use a utility function so rather than doing this if com that out can do function Shuffle array this takes in an array as parameter variable and here you have the shuffle logic here and then you return the array so then to utilize that can simply do cons shuffled array then you simply invoke that function and pass in the array now you can also extend the Prototype safely so if absolutely necessary you want to ensure your ification does not overwrite existing methods and check if the method isn’t already defined so for example you can do if type of array. prototype. Shuffle so if the type of is not a function meaning that’s not defined then if I just copy this and paste it here and uncommon that to tabs so this is an example of how you can extend the Prototype safely by adherance of these guidelines you to ensure that your jav code remains robust maintainable and compatible with other libraries in future updates why is it generally advisable to avoid modifying built-in prototypes in JavaScript it is generally advisable to avoid modifying built-in prototypes in JavaScript because doing so can cause conflicts with third party libraries that rely on the default behaviors of these objects modifying prototypes can also make your code harder to maintain and predict it might break compatibility with future versions of JavaScript or interfere with enhancements in other libraries what are some safer alternatives to modifying built-in prototypes in JavaScript and how can they help maintain code compatibility and predictability some safer alternatives to modifying built-in prototypes in JavaScript include using utility functions where you create Standalone functions to add new functionality without affecting built-in prototypes this avoids potential conflicts and keeps your code isolated and maintainable you can also extend prototypes safely so if you must extend a prototype first check if the method already exists to avoid overriding existing functionality these approaches help maintain co- compatibility and predictability by preventing conflicts with existing or future code and ensuring your additions do not interfere with standard JavaScript Behavior or thirdparty [Music] libraries so to summarize inheritance and prototypes in JavaScript this section has provided a thorough exploration of several key Concepts in JavaScript related to optic R programming we began by understanding inheritance including prototypes and prototypical inheritance which are fundamentals to how JavaScript handles objects and classes we discuss multi-level inheritance where objects inherit properties and methods across multiple levels allowing for a more structured and hierarchical object model the use of property descriptors was covered to control and manage our properties behave including their enumerability and figurability and writability further we examine the distinction between Constructor prototypes and instance members emphasizing the difference
and roles of each in JavaScript programming the process of iterating over both instance and prototype members was covered giving practical insight into how to access and manipulate object properties effectively lastly we address best practices regarding prototype manipulation specifically advising against extending built-in objects this practice while possible can lead to conflicts and compatibility issues especially when dealing with third party libraries overall this section aimed to equip you with a solid understanding of how inheritance and prot types contribute to efficient and effective JavaScript programming promoting better coding practices and a deeper understanding of the language’s [Music] capabilities what is the significance of prototypes and prototypical inheritance in javascripts handling of objects and classes prototypes and prototypical inheritance are crucial in JavaScript because they allow objects to inherit properties and methods from other objects this enables code reuse and efficient memory usage since methods can be shared across instances rather than duplicated prototypical inheritance also supports a flexible and dynamic object model allowing developers to extend and modify objects at runtime which is fundamental to javascript’s object orent programming capabilities how do property descriptors help manage the behavior of object properties in JavaScript and what attributes can they control property descriptors in JavaScript help manage the behavior object Properties by allowing you to control specific attributes of those properties the attributes they can control are innumerable this determines if the property shows up in the forn Loop and object. keys writable this determines if the property’s value can be changed and configurable this determines if the property descriptor can be changed and if the property can be deleted using property descriptors you can precisely Define how properties behave making your objects more secure and predictable why is it generally advised against extending built-in objects and JavaScript and what are the potential risk of doing so it is generally advised against extending built-in objects in JavaScript because it can cause conflicts with third party libraries that rely on the default behavior of these objects this can lead to inconsistent behavior and bugs additionally modifying built-in objects can make your code harder to maintain and predict and it may break compatibility with future versions of JavaScript or interfere with updates and other libraries a better practice is to use utility functions or safely extend prototypes by checking for existing [Music] methods when building software duplicating methods across different objects not only consumes more memory but also goes against the dry principle dry stands for don’t repeat yourself let’s consider how can use inheritance to share common functionality in a way that aligns with best practices imagine we have multiple types of programmer objects such as front-end programmer and backend programmer and they share some common behaviors instead of duplicating methods across both Constructors we can define a generic programmer object that contains shared methods so let’s define a base shape for our shared methods and we name it programmer now this will accept one parameter the should be name so we can set this property for the name and we can Define all of the shared methods that we want so we can do this. code assigning this to Anonymous function and here we log out this. name SCS coding then we can Define this. debug let’s extend this so we can see it more easily function and here we log out this. name is debugging and our last method this. meeting we log it out this. name is attending meetings so here let’s create two instances of this so we can say Alice we call a new programmer to call this Constructor function pass in the name and let’s duplicate so shift option and down arrow I’ll pass in Steven so now let’s do alice. code and steven. code here we save this and we see the expected console log statements so when you define methods directly within the programmer Constructor function each instance of programmer will have its own copy of these methods so here the instance of Alice will have its own methods for code debug and meeting as well as the instance for Steven this approach is less efficient in terms of memory usage because every instance has duplicate methods so remember functions are objects in JavaScript so let’s compare the code functions for these two programmer objects so here I comment this out and then I’ll log out alice. code so that reference and we’ll see if this is strictly equal to steven. code so we are comparing to see whether these functions reference the same object so we see the value of false so in this case Alice and Steven each have their own copies of the code debug and meetings method which is redundant and can consume more memory especially if you create many instances so here can clear this out and expand this so instead of defining these three methods in the Constructor function we can Define it in the Prototype so that these methods will be shared I can Define it here do programmer. prototype. code and then I can assign the function here and I’ll do the same with the other methods so programmer. prototype. debug we’ll copy this and paste it there now we have one more for the meetings programmer. prototype. meetings and then we will copy the implementation here now since we Define on the Prototype we can remove this so now when we compare these functions so alice. code and steven. code we saw the output of true because they are referencing the same function on the Prototype so these functions are shared amongst all instances so when you define methods on the programmer. Prototype all instances of programmer share the same method implementation so this is more memory efficient because the methods are not duplicated for each instance instead they are shared among all instances which is the essence of prototypical inheritance in JavaScript in this case Alice and Steven share the same code debug and meetings method which are defined on the Prototype this reduces memory usage and ensures that all instances benefit from many updates to these methods without needing to update each instance individually what are the benefits of defining methods on the prototype of a Constructor function in JavaScript and how does this approach align with the drive principle defining methods on the Prototype of a Constructor function in JavaScript provides two main benefits the first being memory efficiency methods defined on the Prototype are shared among all instances of the Constructor this reduces memory usage since each instance does not create its own copy of the method the second benefit is code reuse by using the Prototype you avoid duplicating code across multiple instances aligning with the drive principle this makes the code easier to maintain and update in summary prototypical inheritance allows for shared behavior and memory efficiency making your code more maintainable and performant so let’s summarize what we covered so far we implemented methods on the prototype for three reasons one is memory efficiency so defining methods on the Prototype ensures that all instances share the same method implementations reducing memory usage the second benefit is meth method sharing so prototype methods are shared among all instances making it easier to maintain and update the methods and the third is the benefit of inheritance prototypical inheritance leverages the shared Behavior allowing derived objects like front-end programmer and backend programmer to inherit and use these methods without duplication by defining methods on the Prototype you adhere to the principle of efficient memory usage in code reuse making your JavaScript code more maintainable and performant now let’s define more specific programmer roles you can expand this scrolling up we can create a front end programmer Constructor function so this also takes in a name and we’ll create our Constructor function for a backend programmer now we want to call the programmer Constructor function to initialize the name property so we want this version frontend programmer and back programmer to be derived objects that inherit from the programmer Constructor function so in order to call the programmer Constructor function we’ll do programmer. call now for the first argument we will pass the current context so we use the this keyword so this references this current object meaning the instance of the front-end programmer now for the second argument we will pass a name he because that is the expected parameter for the programmer Constructor function so here when we scroll up this Constructor function expects a name so we can also repeat this for the backend programmer so using programmer. call we are calling the programmer Constructor function and setting the context to the new instance of the front-end programmer or backend programmer this ensures that the name property is correctly initialized for each specific programmer type so for setting up the inheritance to enable the front-end programmer and backend programmer to inherit the methods from the programmer prototype we need to set the prototypes to be instances of the programmer Constructor function so to do that can do frontend programmer. prototype this is assigned to object.create programmer. prototype now we repeat this so shift option down arrow for the backend programmer I will also set the Constructor so frontend programmer. prototype. Constructor and set this to front end programmer and we’ll repeat that for the backend programmer so now front-end programmer and backend programmer instances can use the methods to find in program so was access to code debug and the meeting method so let’s actually see this here I will set this here we’ll clear it out let’s common out this console log statement and we’ll utilize these two instances we can do HST say Joe is new front end programmer the name of Joe so here we can say joe. code joe. debug and joe. meeting and we see the expected console log statements defined on the programmer prototype now let’s create an instance of the backend programmer so I can say const and I’ll say gen new backend programmer gen so we’ll call the same methods gen code move this up gen. debug and gen. meting and here we see the expected console log statements so this setup uses prototypical inheritance to share common methods among different types of programmers minimizing redundancy and enhancing maintainability by structuring objects in this way you effectively utilize javascript’s Dynamic nature and prototypical inheritance to create more efficient and organized code this approach ensures that all specific programmer types benefit from updates to the programmer prototype without needing to modify each Constructor separately adhering to efficient coding practices and the principles of object Orient [Music] design how does using programmer. call passing in for the first argument the this keyword and for the second argument passing in the name within the constructors of front-end programmer and backend programmer ensure proper initialization of the name property for these specific programmer types using programmer. call within the constructors of front-end programmer and backend programmer ensures proper initialization of the name property by calling the programmer Constructor with the current instance the this keyword so this way the name property is correctly set for each front-end programmer and backend programmer instance just like it would be for a programmer instance why do we use object . create and pass in for the argument programmer. prototype to set the prototypes of front-end programmer and backend programmer and what is the significance of resetting their Constructor properties we use object. create to set the prototypes of front-end programmer and backend programmer so they can inherit methods from programmer this allows instances of these objects to share the same methods making the code more efficient resetting their constructive properties ensuring the instances are correctly identified as front-end programmer or backend programmer maintaining proper type identification so recap and Core Concepts the term prototype in JavaScript essentially means the parent object in our Constructor functions we define properties and methods often we Define a general Constructor function like programmer which contains common properties and methods so in this case the name property and the code method however we may need to create more specialized objects such as frontend programmer which has specific capabilities instead of duplicating the properties and methods defin in programmer we use prototypical inheritance also called prototypal inheritance to reduce code duplication by doing this front end programmer so this will inherit the properties and methods from the programmer parent object when we call a method such as this code method JavaScript checks the front-end programmer object if it doesn’t find the method definition it looks up the inheritance chain to the programmer prototype and uses the method defined there this setup means we write less code which is easier to maintain and modify because the code is defined in one place and reuse as applications grow reducing code duplication through inheritance makes logical sense so addressing Constructor property issues in prototypical inheritance when implementing inheritance a common issue is the Constructor property this property is important for creating instances Dynam dynamically based on the Constructor function associated with the Prototype so let’s illustrate this with our programmer example here we have the parent object or the base object and we have the derived object the front-end programmer which is a more specialized version of the programmer Base by using programmer. call we inherit the name property but we also want to inherit its methods so to do this we would do frontend programmer. prototype assigned to object . create programmer. prototype right so add a commment here so this is setting up inheritance so we inherit methods so every object has a Constructor property which refers to the function called to initialize the object when we call new frontend programmer so here when we are creating instance a frontend programmer we wanted to call the front-end programmer Constructor this refers to this Constructor function however after setting the prototype to object.create and passing in programmer. Prototype as we did here to inherit the methods The Constructor property of frontend programmer. prototype points to the programmer Constructor function so it’s pointing to this Constructor function as opposed to this one so this can cause confusion so to demonstrate this can log it out say front end programmer. prototype Constructor and strictly equal to this Constructor function just to demonstrate that it is now referencing this Constructor function rather than the frontend programmer Constructor function that we wanted to so can resize this so we can see the output in our console and I’ll save it and here we see the value true so this shows that it’s referencing this Constructor function so to correct this we reset The Constructor property after changing the Prototype right so after we inherit the methods then we need to make sure that we’re referencing the correct Constructor function so to do this we would do front end programmer. prototype do Constructor and we assign this to the front-end programmer Constructor function so now here when we log this out if we save this again we see the value is false because the front-end programmer Constructor function is no longer referencing the programmer Constructor function so to recap whenever you change the Prototype of a function in JavaScript reset the Constructor property this ensures The Constructor property accurately reflects the actual Constructor function for instances preventing potential issues and object creation and inheritance this practice maintains consistency and predictability especially in complex inheritance hierarchies [Music] what is the primary benefit of using prototypical inheritance in JavaScript when creating specialized objects like front-end programmer from a general Constructor function like programmer the primary benefit of using prototypical inheritance in JavaScript is that it reduces code duplication by inheriting properties and methods from a general Constructor function like programmer specialized objects like front-end programmer can use those shared features without having to rewrite them this makes the code easier to maintain and update since the common code is defined in one place and reused across different objects why is it necessary to reset the Constructor property when setting up inheritance using object.create in JavaScript and what potential issues can arise if this step is omitted it is necessary to reset the Constructor property when setting up inheritance using object.create in JavaScript because object.create Chang es the Prototype which can mistakenly point to the wrong Constructor if you don’t reset it the Constructor property might refer to the parent object like programmer instead of the child object like front-end programmer this can cause confusion and bugs when creating new instances as JavaScript won’t know the correct function to use for initializing the objects how does JavaScript handle method lookups in the context of prototypical inheritance and what is the sequence of steps when a method like code is called on an instance of frontend programmer when a method like code is called on an instance of front-end programmer JavaScript follows these steps the first is checking the instance JavaScript first looks for the code method directly on the frontend programmer instance second check the Prototype if it doesn’t find the code method on the instance it looks up the Prototype chain to the frontend programmer. Prototype next it checks the parent prototype if the code method isn’t there it continues up the chain to programmer. prot type where it finds and uses the code method defined there this process ensures that the instance can use methods defined in its own class or any parent class following the inheritance chain so in objector programming in JavaScript Constructors play a crucial role in setting up new objects so Constructor functions essentially refer to the function that is called or invoked to instantiate an object with a given state so we will modify the programmer Constructor that we’ve been working on so we can do function we call it programmer and we’ll specify two parameters so the name and the specialization and we can set that here with the this keyword and this. specialization sign to specialization so now let’s create a derived Constructor function so this will be a more specific type of programmer which we will call a frontend programmer who will also have a preferred framework along with a name and specialization so we have function frontend programmer name specialization and preferred framework so to inherit the name and specialization properties from this parent object rather than having to duplicate that code we do programmer. call for the first argument we’ll pass in the this keyword so that refers to this current object and then we’ll pass in name and specialization because these are the two arguments needed because these are the two parameter variables defined in this programmer Constructor function so now that we’ve inherited those two properties we need to assign our preferred framework now that we implemented that let’s create an instance of front end programmer you can say cons say Steven new frontend programmer Steven for the name the specialization will be front end and the preferred framework speci for that to be react so react is actually a JavaScript library but in this context we will consider it a framework so let’s talk a bit about the new keyword when you use the new operator several things happen first is a new object creation so JavaScript creates a new object in memory second is setting the Prototype it sets the Prototype of this new object to the Prototype of the Constructor function from which it was called so it would be programmer. prototype if you were to do new programmer and it is frontend programmer. prototype for when you do new frontend programmer so third is executing the Constructor The Constructor function is called with the this keyword bound to the newly created object allowing properties and methods to be assigned to this and fourth is returning the object unless the Constructor explicitly returns a different object object the new object is returned by default so let’s discuss the this keyword so in the context of a Constructor function called with the new Operator by default the this keyword refers to the new object being created and second if the Constructor function is called without the new operator then it would refer to the global object so this would be the window object in browsers or the global object and no. JS which can lead to unexpected behaviors and errors Show an example of this here we log out the front end programmer name now do shift option down arrow to create those copies the specialization and the preferred framework let’s resize this so we can see our output in the console and clear this out and when we save it we get our expected output logging our properties so the key takeway using Constructor functions properly with the new operator ensures that the new objects are set up correctly with their intended prototypes and properties it is essential to use the new operator to avoid unintended side effects and ensure that the this keyword behaves as expected within the Constructor function this mechanism is fundamental for implementing inheritance and creating a hierarchy of objects in JavaScript explain the steps involve when the new operator is used with the Constructor function in JavaScript why is it important to use the new operator when calling a Constructor function when the new operator is used with a Constructor function in JavaScript the following steps occur first is a new object creation so a new JavaScript object is created in a memory second is set in the Prototype the new object’s prototype is such as the Constructor functions prototype third is executing the Constructor the Constructor function is called with the this keyword bound to the new object allowing properties methods to be assigned to it and the fourth step is R return the object the new object is returned automatically unless the Constructor explicitly returns a different object it’s important to use the new operator to ensure that the this keyword refers to the new object being created without the new operator then the this keyword will refer to the global object or be undefined if you were using strict mode leading to unexpected behaviors and errors so refactoring with the programmer function so suppose we have a base programmer class and specific subclasses like front-end programmer and backend programmer so here’s you can set up inheritance using a generalized extend function so we have our base programmer Constructor function and a method now let’s create our specific programmer types so that’s function frontend programmer with the name we call programmer. call This And name so let’s copy this and we’ll create our backend programmer so let’s define an extend function that automates the process of setting up prototypical inheritance between a parent and a child Constructor function so we can inherit the methods and properly assign The Constructor function so you can do function extend so for the first parameter variable I’ll specify that to be the child object or child class the second will be the parent so we want to inherit the methods of the parent so we do child. prototype is assigned to object.create parent. prototype so then we will assign The Constructor prototype. Constructor to the child so now using the extend function so with this extend function implemented you can easily set up inheritance for any any number of specific programmer types by simply calling it so we’ll just do extend front end programmer and programmer so I’ll do shift option and down arrow and I’ll pass in backend program so now let’s test the implementation I’ll resize this so we can see in our console so we’ll create instances of the frontend programmer so I say cons Steven sign to new front-end programmer and I’ll do shift option and down arrow and I’ll just change this to be backand programmer with the name of Alice so now we can call and invoke the method that we inherited which is the code method here so it is defined on the parent object which is programmer so we can do steven. code and we could do alice. code and here save it we get the expected output so the benefits of using the extend function the first is encapsulation so by encapsulating The Inheritance logic in the extend function we avoid redundancy and make the code more maintainable and second is reusability the extend function can be reused across the project wherever inheritance is needed promoting consistency and reducing the chance of errors this approach not only streamlines The Inheritance process but also makes the code base more organized and easier to manage by using a generalized method for extending prototypes you ensure the old derived classes correctly inherit from their parent class without manually setting the Prototype and Constructor each [Music] tire what are the benefits of using a generalized extend function to set a prototypical inheritance in JavaScript explain how it improves encapsulation and reusability in your code using a generalized extend function to set a prototypal inheritance in JavaScript has several benefits one being encapsulation the extend function wraps The Inheritance logic in one place so you don’t have to repeat the same code for every new child Constructor this makes your code cleaner and easier to maintain and the second benefit is reusability once you have the extend function you can use it whenever you need to set up inheritance saving time and reducing the chances of mistakes this ensures consistency across your code base overall it makes your code more organized and easier to manage to demonstrate method overwriting we’ll redefine the code method in front-end programmer to include additional Behavior specific to front-end programming So currently we have this derived object the frontend programmer which inherits the properties and methods from the base programmer object so when we call or invoke the code method it simply calls the function derived in its parent but we can override this function it so here before I instantiate it I will scroll up so I’ll resize this then before instantiating it so I can say frontend programmer. prototype. code and assign this to an anonymous function so I’ll say programmer so that Constructor function for the parent. prototype. code. call and then I’ll pass the this keyword so this calls the base implementation defined up here now I can say log and I’ll do back ticks this.name is coding in HTML CSS and Java script so now I will save this and we’re invoking the code method on a frontend programmer we can save it let’s restart the live server so command shift and P live server open let’s resize this right I’ll close this one out open up the developer tools so command shift and J so now I close the sidebar with command b or controlb and I get the expected output I get Steven starts coding which is the output defined in the programmer implementation of the code method and in this derived object where we did method overwriting I also log out Steven is coding in HTML CSS and JavaScript so an explanation of method overwriting this setup showcases how a prototypical inheritance Works in JavaScript when you call the code method on an instance of frontend programmer JavaScript first checks the frontend programmer prototype for this method since we’ve overwritten code in front-end programmer this version is executed which also calls the Base Class method to maintain the general programming Behavior then add specific Behavior so if I were to comment this out it would simply overwrite it and simply log out what we Define here right so just this expected output so some key points the first is Method lookup javascript’s prototype chain means that method lookup starts with the object itself and moves up the chain until it finds the method or reaches the top of the chain and second using the call method for base methods to include the Base Class methods functionality when overriding methods use call to specify the context passing in the this keyword and ensure the base method executes correctly for the deriv class instance by following these principles you can effectively manage and extend behaviors in JavaScript allowing for more flexible and reusable code [Music] structures how do you override the code method in frontend programmer to include additional Behavior while still calling the Base Class method to override the code method in frontend programmer and include additional Behavior while still calling the Base Class method you could do the following first you would Define the new code method on frontend programmer. Prototype inside this method you call the base code method using programmer. prototype. code. call and passing in the this keyword and this will keep the original behavior and then you would add the new Behavior specific to front programmer this way when code is called on a front-end programmer instance it will first run the base code method and then add the new Behavior what is the significance of using call when invoking the Base Class method in an overb method in JavaScript using call when invoking the Base Class method in an overwritten method is important because it ensures the base method runs in the correct context by using call you pass the current object which would be the this keyword to the Basse method so it behaves as if it was called directly on that object this allows the base method to properly access and modify the object’s [Music] properties polymorphism is a key Concept in objectoriented programming so polymorphism stands for many forms and it is what allows objects of different classes to be treated as objects of a common super class through inheritor it’s essentially the ability for different objects to respond to the same method call in different ways first let’s look over this starting code that we’re using we have the extend method which is a utility function that we’re using so that a child object can inherit methods from parent object and make sure that we are resetting the Constructor we have a base object for our programmer which just sets a name property and we Define a method named work who simply logs out a string then we have two derived objects front-end programmer and backend programmer so both of them inherit the name property from this Bas programmer object and we are calling the extend method so we’re inheriting the work method so now we have this spoiler play code let me resize here so implementing polymorphism we have our specialized programmer types which is front-end programmer and backend programmer when want each of them to have a unique implementation of the work method before instantiating an instance of front-end programmer we can do frontend programmer. prototype. workor and assign this to an anonymous function so we are overwriting this method we can do log and we’ll do back tick is designing and coding the front end we have implemented that method overwriting implementation now we can do backend programmer. prototype. workor sign this to Anonymous function and we will log it out back ticks we can say this. name is developing server side logic right let’s create a backend programmer so I’ll scroll up and I’ll do shift option and down arrow and I’ll just name this to be Alice Alice and backend programmer so we’ve instantiated two instances so one for the frontend programmer and one for the backend programmer so using polymorphism so let’s create an array of programmer objects which can be either a front-end programmer or backend programmer so since we are utilizing inheritance we know that a frontend programmer is a programmer and backend programmer is a programmer right so the concept of is a is very important such that our in makes logical sense so by creating this array we’ll say programmers this will demonstrate how each object can use the work method differently according to their specialized class definition so create an array and first I’ll pass in Steven so that front- end programmer and Alice the backend programmer so now let’s iterate through this programmer’s array I can do that with a for of loop so I’ll say for for let programmer of programmers and it will call programmer. workor and so now it will call its unique implementation of the work method so the frontend programmer will call this method and the backend programmer will call its own implementation of the work method so now let’s save this and we’ll see the output in the console so now on the right we see Steven is designing en coding the front end and for the backend programmer Alice is developing server side logic so some key points the first is no type checking is needed so with polymorphism you don’t need to check the type of each object before calling the work method each object knows its own implementation of the work method allowing them to behave correctly according to their specific type and the second is code flexibility and reusability polymorphism simplifies code management and enhances its reusability by allowing you to use a general interface for a range of different objects this example demonstrates how polymorphism can be leveraged in JavaScript to interact with objects from different classes through a common interface enabling flexible and easily manageable code this approach is particularly useful in systems where new types might be added but existing code shouldn’t need extensive changes to accommodate them how does polymorphism allow different objects to respond to the same meth method call in different ways polymorphism allows different objects to respond to the same method call in different ways by using method overloading each object even if they are of different classes can have its own version of a method so when a method is called the correct version for that specific object is executed what are the benefits of using polymorphism in terms of code flexibility and reusability as demonstrated by the programmer example polymorphism increases code flexibility and reusability by allowing objects of different types to be treated through a common interface in the programmer example it means that you can call the same method in this case it is the work method on any programmer object without worrying about a specific type making the code simpler and easier to extend with new types of programmers [Music] understanding inheritance in composition with the programmer function while inheritance is a powerful feature in object Orient programming it’s important to use it carefully to avoid creating overly complex and fragile systems so potential issues with inheritance inheritance should always satisfy the is a relationship meaning that a subass should represent a more specific version of the super class for instance a front-end programmer which is the subass or drive class is a specific type of programmer with programmer being the super class or Base Class however problems can arise if the subass inherits methods that do not logically apply to it leading to an inappropriate relationship example of inheritance complexity so consider a scenario where you are expanding the programmer function to include different types of technical staff in a company so I can resize this Implement a base object so this will be an employee object which has a name parameter this. name and we’ll set the name value now we can create a more specific version of an employee so this subass would be programmer so it takes in a name and we call employee. call then the this context for the first argument referring to this programmer object and and the name so this now inherits the name property if we can create another subass or derived object and this would be a manager so this will also inherit from the employee based object so a programmer is an employee and a manager is an employee so it satisfies the is a relationship so I can call employee. call this and the name so manager inherits from employee now if the employee had programming methods those methods would not logically apply to a manager object so this example shows that the inheritance hierarchy can become inappropriate and bothersome as you don’t want to inherent methods that don’t make logical sense so this would happen in the case if this. employee had a method like code and then we’ll log out right code so it would make logical sense for a manager to have that functionality clear that so as a best practice you want to limit The Inheritance depth in general it’s best to keep inheritance hierarchies shallow ideally not going Beyond one level deep inheritance trees can become difficult to manage and understand favoring composition over inheritance an alternative to inheritance is composition where you build classes out of components rather than using a strict parent child relationship this approach often provides greater flexibility and reduces dependencies between classes when you think of the term composition imagine it as a has a relationship whereas inheritance represents and is a relationship with composition an object includes instances of other objects and their functionality allowing it to have the behavior it needs without relying on hierarchical structure implementing composition with mixins in JavaScript composition can be achieved using mixins where functionality can be mixed into a class for example instead of having a programmer inherit all behaviors specific functionalities like can code can review can design might be mixed in as needed so const can code which would be a JavaScript object literal and within it we can have a method for coding so I’ll say log and I’ll say this.name is coding I can Define another object say can review and I will Define a review method the log and I can say this.name is reviewing code so now let’s actually move this up so I move it up with shift and the up Arrow so I’ll just reorder that so we have these objects defined before the implementation of our programmer Constructor function so let’s create an instance of a programmer so I’ll say cons Steven equals new programmer just pass in my name so now for this programmer Constructor function to utilize the code method and review method we can do object. assign this as the first argument and we’ll pass in can code and can review so I can add a comment here scroll up and I’ll say composing the object with necessary functionalities so now let’s create an instance of programmer so I can say con Steven equals new programmer I’ll pass in my name so then I can do steven. code and steven. review I and save that and I get the expected output so in summary in software design while inheritance might seem like a straightforward way to reuse code it’s essential to evaluate whether it introduces unnecessary complexity often composition provides a more flexible and robust alternative allowing objects to be constructed from discreet reusable behaviors this approach aligns with the principle of favoring composition over inheritance help me to maintain clean and manageable code [Music] bases what is composition composition is a design principle where an object is made up of one or more other objects allowing it to use their functionality it represents a has a relationship meaning that an object contains and uses other objects rather than inheriting from a parent class what are potential issues with inheritance and why is it important to ensure that a subclass satisfies the is a relationship with its super class potential issues with inheritance include creating complex and fragile systems if subclasses inherit methods that don’t logically apply to them it’s important to ensure that a subass satisfies the is a relationship with its super class to maintain logical consistency for example a front programmer should be a specific typee of programmer how does composition offer a more flexible alternative to inheritance in software design and how could it be implemented in JavaScript using mixins composition offers more flexibility than inheritance by allowing objects to include and use functionality from other objects avoiding complex hierarchies in JavaScript it could be implemented using mixins where specific functionalities are added to an object as needed this way you can add functionality without relying on inheritance what is a mix in a Mixon is a reusable piece of code that adds specific functionality to objects or classes in JavaScript mixin are used to share Behavior across multiple objects by copying properties and methods into [Music] them in JavaScript object. assign is a powerful method used used to copy properties from Source objects to a Target object this capability is particularly useful for implementing mixins where common functionalities can be shared across different objects without forming a rigid inheritance structure here’s how you can apply this to a programmer function allowing programmers to have modular capabilities like eating walking and coding so defining mix and objects first let’s define simple objects that contain methods which can be mixed into any Target object so we can Implement a can e method and within it has an e method set this to an anonymous function so I can say this. hunger is decreased and I can log use back ticks this do name is eating so end that with the semicolon now Implement two other objects so the next will be can walk it will’ll have a walk method so I’ll say a function and we will log it out I’ll say this. name is walking we end that with a semicolon and then we have can code so can have a method coding and we will log out this. name is coding end that with a semicolon I’ll just add a period here just to be consistent with the other strings that we’re outputting so using object. assign to mix capabilities you can use object. assign to add these capabilities to a programmer so I scroll up I’ll Define a Constructor function for a programmer this takes in a name parameter variable so we set the name and we’ll set a property for the Hunger so this will be the default hunger level so now we have the mixin functionalities into the programmer’s Prototype so you can do object. assign programmer. prototype so this would be the Target and the source objects that we want to copy will be can eat can walk and can code so now we can instantiate a programmer so I’ll say cons programmer and then new programmer passing in my name and I call each of these methods so first let’s just log this out I can log programmer let’s resize this so we can see it in the console and I’ll save it so here when we expand we see the property for hunger and the name right so our expected properties so now let’s call programmer. Cam see programmer. e and then I’ll do shift option down arrow just to make copies of this and then I’ll say walk and then I’ll say code save that and here I get the expected output so Steven is eating Steven is walking and Steven is coding so to create a reusable mix and function to stream the process of mixing capabilities into different objects you can create a reusable mixin function so let’s define that just at the top so I can say function and I’ll name it mix in now for the parameters we’ll specify a Target object and we will use the rest operator with three dots sources so we can pass in one or more values as an argument so we’ll utilize object. assign the Target and then we will spread the sources right so now when we use this rather than doing object. assign let’s expand this so we can see it better so now I can comment this out and we utilize our Mix end function so here I can say mix in so the target is programmer and we can pass in a variable number of arguments ments so I’ll say can eat can walk and can code so let’s resize this and when I save it I get the same expected output so this approach demonstrates the flexibility of composition over inheritance by composing objects from smaller function Focus objects you can easily extend functionality without the constraints of strict class hierarchy this method not only makes your code more reusable but also makes it modular and easier to understand using Mixon with object. assign allows for dynamic capabilities to be added to objects promoting code reuse and reducing the complexity typically associated with deep inheritance hierarchies this method aligns well with the modern JavaScript best practice of favoring composition over inheritance providing greater flexibility and easier maintenance [Music] how does using object. assign facilitate the implementation of mixins in JavaScript and what are the benefits of this approach compared to traditional inheritance using object. assigned in JavaScript makes it easy to implement mixin by copying properties from multiple Source objects to a Target object adding new capabilities without using inheritance this approach offers greater flexibility avoids complex inheritance hierarchies and promotes code reuse by allowing you to combine only the needed functionalities this section delved into several Advanced topics essential for mastering object or programming in JavaScript we covered creating her own prototypical inheritance so we explored how to establish custom inheritance chains using javascript’s prototype base inheritance system we covered resetting the Constructor the importance of properly resetting the Constructor property when modifying object’s prototype was emphasized to maintain proper linkages we covered calling the super Constructor so techniques for invoking a superclass Constructor within a subass were discussed to ensure that inherited properties were correctly initialized we covered intermediate function inheritance We examined how to implement inheritance through intermediary functions enhancing flexibility and how inheritance is applied we covered method overwriting the course covered strategies for overwriting methods in sub classes to tailor or enhance functionality derived from a super class we covered polymorphism we discussed how polymorphism allows objects of different classes to be treated as objects of a common super class facilitating flexible and dynamic code we covered when to use inheritance guidelines are provided on appropriate scenarios for using inheritance focusing on maintaining a clear is a relationship and we cover mixin the use of mixin was introduced as a flexible alternative to inheritance for composing objects with multiple behaviors or capabilities without forming rigid hierarchical structures by understanding and applying these advanced concepts you can write more robust maintainable and scalable JavaScript applications this knowledge will enable you to leverage the full power of object R programming in JavaScript adapting to various programming challenges with effective Solutions so let’s go over modern JavaScript classes which is syntactic sugar over prototypical inheritance in modern JavaScript the class syntax provides a cleaner and more intuitive way to define Constructor functions and manage prototypical inheritance this new syntax simplifies the creation of objects and their prototypes even though it is essentially syntactic sugar over the existing prototypical inheritance model this syntax introduced in es6 which stands for ecmascript 2015 is part of a specification that enhances JavaScript by adding new language features to modernize it so consider the traditional Constructor function for a programmer that we’ve been working with so if I use the function keyword and I name it programmer I specify two parameters name and prefer language then I set the properties with the this keyword so this.name is assigned to name and this. prefer language is assigned to Preferred language Now to create a method I’ll use the this keyword and I’ll name My Method code signning this to an anonymous function so let’s log to the console back tick this. name is coding in this do preferred language so now I can create an instance of this with the new keyword to create a new object in memory so I’ll say cons programmer is assigned to new programmer I’ll pass in my name Steven and the preferred language is Javascript so now I can call programmer. code and we can output that to the console and here we see our expected console log statement so let’s rewrite this Constructor function using modern class syntax which makes it clearer and more structured so we can comment this out so this is the syntax that you would use in modern JavaScript applications you would use the keyword class and then you name that class so in this case it’s programmer and now you would Define a Constructor function so classes in JavaScript have one Constructor function and this is the function that has called when you use the new keyword so it is named Constructor right so that’s the keyword and in this case the parameters our name and preferred language and within it we set our properties so this not name set a name in this preferred language is set to Preferred language so now to Define our method we’ll name it code and we will log the same output statement so let me just copy it here just to save us some time so this is the modern way to define our classes in JavaScript rather than using Constructor functions so and when we save it we will get the same output right so once again we get step’s coding in JavaScript so understanding the underlying functionality despite the use of the class keyword the underlying me mechm Remains the Same so consider the type of operator even with the class syntax programmer is still a function in terms of javascripts type system it’s specifically a Constructor function so let’s log that out so I can demonstrate that and then I do log and then tab if I do type of and then programmer we will see that the type is a function so when we save this we see that it is a function es5 compatibility for environments that do not Support es6 classes tool like Babel available at babeljs doio can trans file this modern JavaScript back to es5 compatible code ensuring that the classes work across all browsers so consider the benefits of using class syntax the first benefit is Clarity and simplicity the class syntax is easier to read and understand especially for developers coming from other object oriented languages like Java or CP the second benefit is encapsulation using class syntax encourages better encapsulation and a more declarative structure for defining object Constructors and methods and the third benefit is standardization it offers a standardized way of object creation and inheritance that aligns with other program languages using the learning curve so in summary by utilizing modern JavaScript class syntax you could write cleaner more maintainable code while still leveraging the powerful prototypical inheritance model that JavaScript offers this approach not only enhances readability but also simplifies complex coding structures making it an essential skill for developers working in modern JavaScript environments how does the class syntax and modern JavaScript improve the process of defining Constructor functions and managing prototypical inheritance the class syntax in modern JavaScript makes it easier and clearer to create objects and their prototypes it provides a straightforward way to Define Constructor functions and methods making the code more readable and organized compared to the older method even though it looks different it still works the same under the hood what are the benefits of using class syntax over traditional Constructor functions in JavaScript there are three main benefits of using class syntax over traditional Constructor functions in JavaScript the first being Clarity the class syntax is easier to read and understand the second benefit is encapsulation it helps organize code better by keeping related methods together and the third benefit is standardization it aligns with how other program languages handle classes making it easier to learn and use so for your exercise update this function Constructor to use the es6 class syntax so here I’ll call item. display and I get the output of the name of the item and the quantity so to implement this I’ll comment this out so now I’ll do class and name the class grocery item then curly braces and then I’ll Define The Constructor function which will be executed when I use the new keyword so the parameter is the name and the quantity I just assign this with the this keyword to set the properties and for the quantity Now define a method so I’ll say display and I’ll just copy this console loog statement and face it here so let’s clear our console and I’ll save it and we get our expected [Music] output in JavaScript functions can be defined using either function declarations or function Expressions both methods serve similar purposes but have key differences in Behavior particularly regarding how they are hoisted so let’s consider function declarations function declarations are hoisted to the top of their containing scope this means that they are moved to the top during the compile phase allowing you to call them before they are physically defined in the code so to demonstrate this I’ll Implement a function I’ll name it GRE and then I’ll log out hello world now to demonstrate function hoisting I can call or invoke the Greet method before it is defined so if I save this I get the expected output so because of hoisting JavaScript will move this function to the top of the file during the compile phase so now considering function expressions in contrast function expressions are not hoisted which means you cannot call them before they are defined in the code trying to do so will result in a reference error so to demonstrate this I’ll just comment this out we don’t need it I can say cons say goodbye set this to an anonymous function and then we will log out goodbye so now if I try to invoke it for it is defined let’s clear this out and I save it here we see we get a reference error so you can comment this out so now let’s apply this concept to the programmer class context so we scroll up now let’s consider this class that we defined in our previous lesson when working with classes it’s crucial to understand that like function Expressions class declarations are not hoisted this means you must declare a class before you can instantiate it so let me move above it just to demonstrate that we cannot instantiate it before it’s being defined I can say conev is assigned to a new programmer I’ll say my name and the preferred language of JavaScript and I’ll just save that and here we see we get a reference error we cannot access programmer before it’s initialized so using class Expressions just as with function Expressions classes can also be defined using a class expression syntax which is not hoisted and allows for more Dynamic declarations so to demonstrate that I’ll just to find this here I can say cons my programmer class set this to the keyword of class and then curly braces and then I want it to have the same functionality as this programmer so I’ll just copy this over let’s clear let’s common out this line so we don’t need that so we’ve created this class expression and let’s create an instance of it below its declaration so I can say con programmer and new my programmer class pass in Steven and in this case I’ll say JavaScript and then we can call the method programmer. code let’s clear this out and we’ll save it and we get our expected output so here we are creating instance of it after its declaration now if I were to move it up so I’m moving it up with option up Arrow end up here so now that I try to instantiate instance of this before its declaration if I save it now then I get a reference error note that you wouldn’t actually use this class expression syntax very often but I wanted to demonstrate it just show that it is possible in conclusion choosing between function declarations and expressions or class declarations and expressions can impact how you structure your JavaScript code for Simplicity and Clarity especially when defining Constructors and methods within a class using class declaration syntax is often preferred however being aware of hoisting rules is crucial for avoiding runtime errors and ensuring that your JavaScript code executes AS intended [Music] what is the main difference in Behavior between function declarations and function Expressions regarding hoisting in JavaScript the main difference is that function declarations are hoisted to the top of their scope so you can call them before they are defined in the code function expressions are not hoisted so you must Define them before calling them otherwise you’ll get a reference error why is it important to understand hoisting rules when working with class declarations in JavaScript it’s important to understand hoisting rules because class declarations are not hoisted this means you must define a class before you use it or you’ll get an error knowing this helps you avoid mistakes and ensures your code runs [Music] correctly an object going in programming especially within JavaScript classes we distinguish between instance methods which act on instances of the class and static methods which are called on the class itself and are often used as utility functions so let’s consider the programmer class that we have defined so whenever we create an instance of a programmer it has access to the code method to demonstrate that we have dev. code when we save that we get the expected output which is this console log statement so now let’s define a static method which should be accessible through the programmer class so I’ll use the static keyword and then I’ll name this method compare skill and this will accept two parameters so I’ll say programmer one and programmer 2 and this will return a Boolean value comparing programmer one and their preferred language and strictly equal to programmer 2. preferred language so let’s create another instance of this programmer so I’ll do shift option and down arrow to create a copy and I’ll name this Dev to I’ll change the name to be Alice now to compare it I will log the result of that pan value so I’ll use let me scroll up and see better and I’ll say log I’ll do programmer and then the static method so I do dot compare skill now I’ll pass in Dev and Dev 2 and we’ll expect this to be true because they’re using the same programming language so when I clear this first and then save it so we get the output of true because they both have JavaScript as their preferred language so let’s scroll back up so we can review our class so instance methods like code are used to perform actions that are relevant to the individual objects created from the class and static methods such as compare skill are used for operations that are relevant to the class as a whole or involve multiple instances of the class but don’t depend on any single object state so understanding the utility of static methods static methods are particularly useful for utility functions where the operation does not depend on the state of a particular instance but rather on the parameters provided to the function this makes them similar to functions provided by the math object in JavaScript such as math. round or math.max which perform General utility operations and are not tied to a specific object in conclusion understanding when to use instance methods versus static methods in your javascrip classes can significantly impact the design and functionality of your applications instance methods are best for manipulating or utilizing the state of individual objects while static methods are ideal for tasks that require a broader scope ones that involve the class itself or interactions between multiple instances this distinction helps in organizing code logically and maximizing the efficiency and readability of your JavaScript applications what is the difference between instance methods and static methods and JavaScript classes instance methods are used on individual objects created from a class and act on the data within those objects static methods are used on the class itself and are typically utility functions that don’t rely on the data of any single object why are static methods useful in JavaScript and when should they be used instead of instance methods static methods are useful for tasks that don’t depend on the data of a specific object but rather on parameters provided to the method they should be used for General utility functions or operations involving multiple instances of the [Music] class so for your exercise to add a static method to the grocery item class you can Define the method with the static keyword so static methods are called on the class itself rather than on instances of the class so for your exercise create two instances of the grer item class and have each of these objects have different names and quantities then Implement a static method named compare quantities to compare the quantities of the two items and print out the result so if the quantity of item number one is greater than item number two then log that the name of the first item has more quantity than the name of the second item if the quantity of item one is less than item two then log that the name of item two has more quantity than the name of item one otherwise output that both of them have the same quantity so to implement the compare quantities static method I’ll use the static keyword and we name it compare quantities then it takes in item one and item two then I’ll use an if statement so if item 1. quantity is greater than the quantity of item two qu then I will log use back tick so I can use interpolation item one. name has more quantity than item 2. name else if item 1. quantity is less than item 2. quantity then I will log out item 2. name has more quantity than let’s fix this move that y then item one. name else will be the case when they’re equal and log out item one. name and item 2.n name have the same quantity so let’s create two instances of the grocery item class so I’ll say cons I’ll call this apple equals new grocery item and then the name is Apple and the quantity is four so I’ll just copy this line with shift option and down arrow and I’ll rename this to be banana let’s just copy this over and I’ll update this value to be seven so now I can call this static method with grocery item do compare quantities of apple and banana so let’s save that and here we get the expected output that banana has more quantity than Apple let’s switch these values around just so we get the expected result we’ll clear it out and then we say it you get apple has more quantity than banana and in the case when they’re equal we get the apple banana have the same quantity let’s go over understanding the this keyword in different contexts with the programmer class the this keyword in JavaScript behaves differently based on how a function is called this Behavior can lead to unexpected results especially when functions are detached from the object context so let’s first illustrate this with a programmer Constructor function so we’ll use the function keyword we’ll name it programmer this accepts a parameter of name so we’ll set the name property then we’ll Implement a method named code so we assign this to an anonymous function then log and then tab and we will log out the this keyword so let’s create an instance of the programmer object so we’ll name it programmer assign to a new programmer and I’ll specify my name so Steven and then I will call the code method so now want to Output this and save it here I see outputs this instance of the programmer so that object and memory so here we see the property of the name and the code method so now let’s consider detaching a method when you detach a method from its object and call it independently the this keyword loses its original context in JavaScript functions are objects so we know that this method or in other words this function is just an object in memory so to get access to it I can call it detach code methods and I set this to a reference to that object right so functions are objects and so now this identifier detach code will reference this function however because it’s detach it has lost context of its this keyword so now let’s invoke this so I can say detach code and then let me clear this out so we can see it and so when I save it here I see in the original instance when I call code it logs out the programmer object however when I call detached code it logs out the window object so in web browsers the this keyword will reference the window object and in nodejs it will reference the global object so how can we fix this we can utilize strict mode so we go up here in JavaScript strict mode changes the behavior of the this keyword in function calls not associated with an object so in strict mode the this keyword becomes undefined instead of defaulting to the global object so if I were to use use strict a string end it with a semicolon and I would specify this to be the first line in the program so now let’s clear this out and when I save it the first time when I call the code method and it console logs the this keyword it references the current object that it’s referring to however in the case when we call a detach method previously it was referencing the window object but now since we’re in strict mode it outputs undefined so here we’re using a Constructor function now if we were to to use classes they implicitly use strict mode to avoid these issues instead of using a Constructor function I’ll specify it to be a class so I Define The Constructor method this sets the name property and I’ll Define a method for code and it outputs to this keyword so let’s comment this out so we don’t need to explicitly specify use stript let’s clear this out and when we save it so because we’re using the class syntax it is implicitly using strict mode so let’s cover the benefits of strict mode in class bodies the first benefit is safety it prevents functions from unintentionally modifying Global variables which can lead to difficult to track bugs and the second benefit is consistency it ensures that the this keyword behaves consistently making the code more predictable and less prone to errors in conclusion understanding how this keyword behaves in different context is crucial for JavaScript development ERS by using strick mode and being cautious of how methods are called developers can write more robust and secure code the implicit use of strick mode within class bodies in modern JavaScript helps enforce these best practices preventing common mistakes associated with the this keyword in global [Music] context what are the potential consequences of detaching a method from its object context in JavaScript detaching a method from its object context in JavaScript can cause the this keyword to lose its original reference instead of pointing to the object it belongs to that this keyword May point to the global object like window in browsers or be undefined in strict mode this can lead to unexpected behavior and bugs because the method no longer has access to the object’s Properties or methods how does strict mode in JavaScript enhance code safety and consistency particularly in the context of class body strict mode in JavaScript makes code safer and more consistent by changing how certain things work in class bodies it ensures that
the this keyword is not accidentally pointing to the global object instead if the this keyword is not set it will be undefined which helps prevent bugs strict mode also stops you from making some common mistakes like creating Global variables by accident making the code easier to understand and less prone to errors so understanding abstraction with the programmer class abstraction and programming involves hiding complex implementation details and exposing only the necessary parts of an object this is commonly achieved through private properties and methods let’s apply the concept of abstraction to a programmer class where certain details like the programming language proficiency level might be internal to the programmer’s operations let’s consider the first approach where we achieve PR private properties through the naming convention so one approach is to use an underscore prefix to indicate a private property so if we create a programmer class and we have the Constructor picking a name in language then we can do this doore language language assign to language I’ll just add a comment here it’s not truly private just a naming convention so now if we were to instantiate it cons programmer new programmer passing in Steven and the language of JavaScript here I log out it do programmer doore language so here it outputs JavaScript so we still have Public Access but the use of the underscore indicates to the programmer that this is supposed to be a private property now there are issues with this and the issue is that this method relies on the naming convention and does not provide true privacy properties are still accessible from outside the class so let’s consider a second approach which uses es6 symbols a more secure way to implement private properties is using es6 symbols which provides a way to create unique identifiers so before I create my class I will saycore language instead it to a symbol value which is a unique identifier unique value so rather than setting it through notation underscore language I’ll use the square bracket notation and I’ll pass in the symbol as a key just to demonstrate this this is more private but still accessible through reflection so here if we try to access underscore language that’s not a property defined in it so we can actually access this but it is not straightforward but the demonstrate you could I will log out object. getet own property symbols it’ll pass in the identifier for our object let’s save that so here we see an array of symbols so using this if I want to get the value at the zeroth index I could do so so if I want to access that value at the zeroth index I can say cons language symbol it’s assigned to and not just cop this value over and the zeroth index so I can use this as the key in order to get the language do log programmer and then square bracket notation the language symbol and it outputs the value of JavaScript so here we see that this property is still accessible through the outside although it is not intuitive so some observations symbols provide a pseudo private mechanism as they are not accessible through normal property access methods however symbols can still be accessed through object. getet own property symbols so it’s not completely private so let’s consider private methods using symbols similarly you can use symbols to create methods that are not accessible directly via the class instance so let’s say if I were to define a symbol I’ll say underscore code and set that to a new symbol so unique value now I can create a private method so use square bracket notation then the symbol as the name of that method and then let’s log and I’ll say this.name is coding in and I’ll say thisor language and that with a period and a semic so in conclusion while symbols enhance privacy they do not provide a foolproof solution for private properties or methods for truly private class Fields es 2022 introduces private class fields and methods using the hash symbol or the hash prefix so this also called the pound symbol or Octor symbol but I’ll refer to it as the hash symbol and this is the best approach going forward for ensuring data encapsulation and adhering to the principles of abstraction and object orent programming so let me clear all this so we can start from scratch I’ll clear this out now we can say class programmer now I’ll create a private property name it language and here we see it as prefix with the hash symbol now let’s define our Constructor which takes in a name in a language and we do this dot language is assigned to the language and let’s set the name to this. name the name now we can define a truly private method we can do so with hash and then code so we can say log coding in thish language now let’s create an instance of this class so we’re creating a new object and memory programmer passing in my name and the language let’s log this programmer object and when we output it we can expand it and we see the name and the language now if we try to access the property of language let’s try doing that here programmer dot if I do hash and then language here we see the private fi hash language must be declared in enclosing class so in other words it is not accessible if wey to access it by language we get the value of undefined so this method ensures that the language property and code method are completely private it encapsulated within the programmer class and not accessible from outside this approach align closely with the principle of abstraction keeping implementation details hidden and interfaces clean and [Music] straightforward what are the benefits and limitations of using symbols for creating private properties in JavaScript classes you using symbols for private properties in JavaScript classes has benefits and limitations now the benefits are improve privacy symbols make properties less accessible through normal methods adding a layer of privacy another benefit is unique identifiers symbols create unique property Keys reducing the risk of naming collisions now the limitations the first limitation is that it is not fully private properties created with symbols can still be accessed using methods like object. get own property symbols another limitation is complexity using symbols can make the code harder to read and understand as accessing these properties isn’t straightforward how do private class Fields introduced in es 2022 improve data encapsulation compared to previous approaches private class Fields introduced in es 2022 improve data encapsulation by providing true privacy for properties and methods using the hash prefix the these private fields are completely hidden from outside access ensuring they can only be used within the class this prevents accidental or unauthorized access making the code more secure and easier to maintain compared to previous approaches like naming conventions or symbols which didn’t fully hide the data so your exercise is to implement private properties and methods with es 2022 in a grocery lless application in this exercise you will create a grocery list class and a grocery item class to manage a grocery list application the goal is to understand and apply the concept of abstraction by using ES 2022 private properties and methods this will help you hide the implementation details and expose only the necessary parts of these classes so let’s do a quick overview of the instructions for this exercise the first is to create the grocery item class this class should have private properties for the items name and quantity it should include a Constructor to initialize these proper properties and Implement a method to display the item details this method should be public and provide a formatted string of the items details second create the grocery list class this class should have a private property for the list of grocery items include methods to add an item to the list remove an item from the list by name and display all items in the list and ensure that the internal list of items is not directly accessible from outside the class now the third instruction is using es2020 to private properties and methods use the hash prefix to Define private properties and methods in both classes ensure that no implementation details are exposed outside the class so the example code here is the starting point for the grocery item in grocery list classes so we’ll create a grocery item class so we have a Constructor which takes in the name and the quantity now it will have a public method to display item details so I’ll name this display item now let’s create our grocery list class and I’ll scroll up so we can see it better so this will have a Constructor it will have a public method to add an item to the list so we name that add item and that takes in name and quantity we have a public method to remove an item from the list by name can name that remove item pass in the name as the parameter and a public method to display all items in the list name that display list so this is this is our starting point code so now the task checklist first Define the grocery item class create private properties name and quantity implement the Constructor to initialize these properties and implement the display item method to return a formatted string of the items details task number two Define the grocery list class create a private property items to hold the list of grocery item objects implement the ad item method add a new grocery item to the list implement the remove item method to remove an item by name implement the display list method to display all items in the list the third task is to test the classes create an instance of grocery list add multiple items to the list display the list to ensure items are added correctly remove an item and display the list again to ensure the item is removed correctly by completing this exercise you will gain hands-on experience with es 2022 private property and methods enhancing your understanding of abstraction and encapsulation in JavaScript so now for our grocery item let’s declare our private properties which is name and quantity now we will set these prate properties so this as name is set a name and this quantity is assigned to quantity now now to display the items we can log and actually I will have it return the value rather than log so I use back ticks and I can say item this and then hash name and then quantity this quantity so we’ve implemented that class let’s expand this so you can see a it better let’s scroll now we want to create a private property for our list of grocery items so we’ll name the items and we The Constructor is where we will initialize this array so this items assign to an empty array I’ll scroll that so for adding an item I will create a new grocery item object so item new grocery item passing in the name and the quantity so now I will push to the end of the array so item push adding that new item so now for the remove method say this items is assigned to this. items we use the filter method we pass in a callback function this is a predicate so the item. display item so that output here which includes the name and the quantity so if that includes I’ll use back tick item and then the name then in that case it would be filtered out in the case when it is not included and now to display everything I can say return this items. map then pass in our call back item display item and I can say do join and we’ll specify a new line so all the items will be displayed on their own line so now let’s resizes so we can see our console so now we want to create a new instance of the grocery list new grocery list grocery list let’s add some items so do add item so I’ll say apples the quantity of five and I’ll do shift option down arrow so to add bananas and we’ll specify the quantity to be three then we can call log grocery list dot display list let’s save that so here we see the expected output so it’s calling the display item method for each of them so now let’s remove an item so I can say grocery list. remove item so remove apples and then let’s copy this and we will call it again so now let’s say if I clear it and we run it again we see for the first output is apples and bananas and after we call the remove method it successfully just displays what is left in our grocery list which is bananas weak map provides a way to securely store private data for an object without preventing garbage collection when the object itself is no longer in use here’s how you can use weak map to implement private properties and methods within the programmer class so let’s define underscore language and instantiate a new week map and consor work new week map so this data type allows it to store key value pairs so now we will create a programmer class The Constructor will take in a name and a language so now we can set the name to be a public property but in this case we want the language to be private I’ll just add a comment here to better describe what we’re doing so store language in a week map with this as the key so I can set underscore language do set so here we are set in the week map so for the first argument we specify the object so in this case it would be the this keyword which refers to this current programmer object and we will specify the value being language right so the value that we pass in to the Constructor so now let’s store a private method in a week map so underscore work right this week map that we created up here we will set the this keyword referring to this current object and for the value we would specify a callback function So within it we will log use back ticks this.name is coding in do the weak map which is named uncore language. getet and the this keyword as its key so now we can save that so now let’s Implement a method named code so this is a public method and this will call the private method that we have stored in the weak map so I add a comment access and invoke the private method so underscore work which is the name of that week map call the get method and we pass in the this keyword so this current object which is the key and now we need to call or invoke this method so open and closing parentheses to call that method so now let’s create instance of this programmer class so I’ll say cons programmer new programmer with my name as Steven and the language of JavaScript and let’s call that public method code and we save that we see Steven is coding in JavaScript so we call the code method we this call the method defined in our weakmap which is a private method so let’s go over a discussion of the week map data structure and the benefits in usage so first is garbage collection A major benefit of using weak map is its handling of keys if there are no other references to a key object in this case an instance of programmer it can be garbage collected this helps prevent memory leaks and applications where objects are dynamically created and destroyed the second benefit is encapsulation using weakmap for storing private data ensures that these details are not accessible from outside the class this is much more secure than using properties prefixed with an underscore as these are only conventionally private third is Arrow functions and the this keyword Arrow functions do not have their own this keyword contexts instead they inherit the this keyword from the enclosing execution context within underscore work this refers to the programmer instance allowing access to the instance’s name and other properties securely stored in the week map so let’s consider an alternative with a single week map you can also group all private properties into a single weak map entry per object though this might make the code slightly more verbose short an example of that let’s comment out this implementation we will create a new one so I’ll say cons private props new week map so now we will create a new implementation of programmer so the Constructor takes in the name and the language let’s remove that underscore so our C braces now we will say private props move this up do set so for the key it is this current object so the this keyword and for the value we will specify a JavaScript object so here we will store key value pairs so we’ll specify the name the language so now let’s specify the work method so we’ll specify a call back so we will log back tick private props doget the this keyword and the property of the name is coding in private props doget the this keyword. language so now we Implement our public method code and this will call Private props doget this keyword and calling the work method so now when we output it we get the same expected result to in conclusion using weakmap for managing private data in JavaScript classes provides a robust way to ensure encapsulation and data security this approach is particularly useful in scenarios where data privacy is crucial and helps maintain clean API boundaries within your [Music] classes how does using weakmap for private properties and methods enhance data encapsulation and Security in JavaScript classes using weakmap for private properties and methods enhances data encapsulation and security by ensuring that private data is not directly accessible from outside the class this keeps the implementation details hidden providing a secure way to manage private data within objects what are the benefits of using weakmap in terms of garbage collection and how does this prevent memory leaks in JavaScript applications weak map allows objects to be garbage collected when there are no other references to them even if they have private data stored in the week map this helps prevent memory leaks by ensuring that memory used by objects no longer in use is freed up automatically what distinguishes week map from the es 2022 hash Syntax for private properties and methods and why might you choose to use week map weak map allows you to to store private data for objects without preventing their garbage collection when they’re no longer in use making it useful for managing memory efficiently the es 2022 hash syntax provides built-in support for private properties and methods making them truly private and not accessible from outside the class you might use weak map if you need private data that can be automatically cleaned up by garbage collection to prevent memory [Music] leaks so we’ll start by demonstrating how to store a private property in a programmer class using a weak map and then show how to define property accessors so let’s set language to a new week map and we’ll Define a programmer class so once again we have our Constructor setting the name in the language let’s remove that underscore we’ll set the name and the language with the weak map so but this operat Ator or this keyword rather for the current object and the language so this property is public and this is private now we’ll Define a method named get language in order to access this private property with the private value which is the language so we will return language doget and then the this keyword so we’ll create a new programmer so cons programmer is assigned to new programmer Steven and the language of JavaScript so now let’s call the get language method we need to call the console log so log and then programmer doget language save that and we get the value of JavaScript so now using object. Define property to define a getter for cases where you want the property to be accessible more like a property rather than a method you can use object. defin property so rather than calling the get language method we prefer to access it through a property named language so here we can set object. Define property so the first argument is the this keyword so this current object now we will name the property so this case I’ll name it to be language and then we’ll pass in an object so use the get keyword word set this to Anonymous function and here we return language. getet and this right so we don’t need this method anymore now we can access it through notation through this property that we created so rather than doing get language you can access it with language as that is the name of the property that we specified here so now when we call it let’s clear it actually and let’s say save it we get the expected result as this is calling this function defined here cleaner es6 Syntax for Getters and Setters in es6 Getters and Setters can be defined within the class body providing a more concise and readable way to access properties so let’s delete here we Define the property and let’s define a getter so we use the get keyword and then space and then the name of the property so we’ll name it language and this return returns right so we’re using the weak map here get and then the this keyword so now let’s define a Setter so we’ll set the language the parameter will be new language let’s move this up so if new language is falsy in the case when it’s an empty string for example then we’ll throw an error saying language cannot be empty and that with the semicolon otherwise we will update the value stored in the week map so set so the key is the this keyword so this current object and we’ll update the language all right so now we can access language as if it were a property so here let’s clear this when we save it we get the expected result so now let’s update the language so I can say programmer. language and I’ll set this to a new language such as python so let’s scroll up so let’s log this out programmer. language and I save it here I see the value has been successfully updated to be python as when we set this value so programmer. language is assigned to python we are calling the setter let’s expand this and I’ll discuss it so first let’s consider the weak map which we Define here this provides a way to securely store private data associated with an instance so object. Define property this method is useful when you need to create Getters or Setters that appear like properties but are backed by methods it allows for fine grain control over property characteristics es6 Getters and Setters these provide syntactic sugar that makes accessing and modifying properties intuitive and similar to accessing traditional class properties this method is particularly useful for validation logging or handling side effects during property access in conclusion these different approaches allow JavaScript developers to encapsulate and protect data within classes effectively ensuring the implementation details are hidden and that public interfaces are clean and easy to use using these features appropriately can help maintain and scale large code bases making your code more robust and easier to manage how do es6 Getters and Setters enhance the encapsulation and control of property access within classes es6 Getters and Setters enhance encapsulation and control by allowing you to Define methods that get or set property values this provides a way to add logic when accessing or modifying properties such as validation or transformation while keeping this syntax similar to regular property access what are the benefits of using the get and set keywords in es classes compared to traditional methods for accessing and modifying properties using get and set keywords in esess classes allows for more intuitive and cleaner Syntax for accessing and modifying properties similar to regular property access they also enable adding custom logic such as validation when getting or setting a property enhancing encapsulation and [Music] control so let’s cover inheriting and extending the programmer class we’ll start with a base programmer class that has a Constructor for initializing a programmer with a name and a basic method for coding so we’ll specify our class and our Constructor except a name now we’ll just set this name property and we have a simple method for coding so this will log out do back ticks this.name starts coding so we’ve implemented our Base Class so now let’s create a derive class which would be a front-end programmer so we will extend this General base programmer class to create a front-end programmer class that includes additional properties and methods relevant to front-end programming so Implement that just below it so it would be class frontend programmer and we’ll use the special keyword extends programmer so the derived class will inherit from the base class when we use the extend keyword and this is because the front-end programmer is a programmer so this is how you would achieve inheritance using the es6 class syntax so we inherit the properties and the methods from the base class so let’s create our Constructor function this accepts the name and we’ll specify an additional parameter which will be tools so we can call Super and then name and so this keyword super this calls the super class Constructor with the name argument so we’ll call this Constructor of the base class so let me add a commment here just to better describe that I’ll say calls the super class Constructor with the name now we’ll set the tools based on the argument passed in so I’ll add a comment to describe this as well I’ll say additional property specific to frontend F camers so now we will specify its own code method so we’ll say super . code so this calls the generic code method from the programmer based class and I we add additional functionality so I’ll log out I’ll use back ticks I’ll say this. name codes with I’ll say this. tools land it with a period and a semi let me extend this so we can see it better so now we can add methods specific to a frontend programmer so I’ll say design let me scroll up so we can see now I will log out back TI this.name also designs the user interfaces so here we see our derived class frontend programmer is a more specific version of the programmer Base Class and has additional functionality so now let’s use this deriv class we create an instance of the front end program class and we’ll demonstrate the use of both inherited and specific methods so I’ll say cons front and Dev assign to a new front end programmer I’ll pass in my name and I’ll specify the react JavaScript library as the tool so let’s resize it so we can see the output and I’ll say front end Dev and we call the code method we save it so here we see Steven starts coding and Steven codes to react so that first log statement Steven starts coding is implemented in the general or the base programmer class right that is because we called super. code and then we see it outputs the log statement in the front end programmer so I resize it when it says Steven codes with react so now let’s call another method I’ll say frontend dev. design Implement that and here we see this log statement we specified here which is Steven also designs the user interfaces so let me expand this and we can discuss it so we covered inheritance so the front-end programmer class inherits from the programmer Base Class gaining access to its methods while also being able to introduce new properties and methods or override existing ones like how we did with this code method we use the keyword for super so the super keyword is essential for calling the Constructor of the base class so in this case the programmer class from the derive class it ensures that all the initialization logic in the super class is properly executed before additional setup in the subass and we covered method overwriting the code method is overwritten in in front-end programmer to extend its functionality but it also calls the superclasses code method to maintain the general coding behavior in conclusion this example clearly illustrates how to effectively use inheritance in JavaScript to create a hierarchy of classes where derived classes extend and specialize the behavior of their base classes this pattern is crucial for structuring complex applications in a way that promotes code reuse and logical organization [Music] how is the super keyword used in the front-end programmer class the super keyword in the frontend programmer class calls the Constructor of the programmer Base Class ensuring that the name property is initialized correctly before adding more Properties or methods specific to frontend programmer what are the benefits of using inheritance when extending the programmer class to create the front end programmer class using inheritance to extend the programmer class allows the front-end programmer class to reuse existing code add new properties and methods and override existing ones making the code more organized and easier to [Music] manage let’s go over method overwriting with es6 classes we will start with a base programmer class that has a generic work method then we’ll create a specialized front-end programmer class that extends programmer and overrides the work method to add specific behavior so let’s Implement our Base Class so that will be a programmer we’ll implement the Constructor to accept a name parameter so this.name is assigned to name now let’s implement the generic work method so we’ll say log and tab back tick then this.name is solving problems so this is our Base Class which we will extend so we Implement class front and programmer extends the programmer base class because the frend programmer is a programmer so this accepts and name and we call the super classes instructor so comment initialize the Base Class part of the object and we will override the work method so we’ll call super. workor so this calls the Base Class method and now we will add our own specific functionality so I’ll say log say this.n name is also designing and implementing UI components so now let’s use our derived class say cons I’ll say Steven equals new front end programmer so it accepts a name parameter so we’ll pass Steven as the argument now we’ll say steven. and we’ll save it and here we see our expected output so calls super. work so calls the Base Class implementation of the work method so we see Steven is solving problems and then we will log out Steven is also designing and implementing UI components so let’s expand this so understanding the method lookup and the super keyword so method lookup when a method is called the JavaScript engine first looks for it on the object itself if it can’t find the method it walks up the Prototype chain to find the method in the parent class so in this case frontend programmer its prototype or its parent is the programmer Base Class and able to achieve inheritance through the extends keyword so using the super keyword the super keyword is crucial in subclass methods to call corresponding methods defin in the super class this feature allows subclasses to enhance or modify the behavior methods they inherit without completely rewriting them thus promoting code reuse and reducing duplication in conclusion by overriding methods and using the super keyword effectively you can ensure that subclasses not only tailor inherited methods to their specific needs but also leverage and extend the functionality provided by the super classes this approach is beneficial for maintaining logical and maintainable code and objectoriented JavaScript applications as it minimizes redundancy and ensures a clear and efficient inheritance structure [Music] what is method overwriting in es6 JavaScript classes method overwriting in es6 jvip classes is when a subass provides a specific implementation for a method that is already defined in its parent class replacing the parents method with its own version how does method look up work when calling a method method on an object in JavaScript when calling a method on an object in JavaScript the engine first looks for the method on the object itself if it’s not found it checks the object’s prototype and continues up the Prototype chain until it finds the method or reaches the end of the chain what is the role of the super keyword in a subclass methods in JavaScript the super keyword in subclass methods and JavaScript is used to call methods from the parent class allowing the subass to build on or modify the behavior of those methods so let’s summarize what we covered in this section es6 classes we explored how es6 class syntax provides a clearer more concise way to define Constructor functions and manage inheritance classes make the the structure of object ored JavaScript cleaner and more similar to other programming languages which helps in organizing code and improving readability hoisting the concept of hoisting was discussed to understand how JavaScript interprets function declarations and variable declarations differently we noted that function declarations are hoisted to the top of their containing scope allowing them to be used before they appear in the code static methods we learned about static methods which are called in the class rather than on instances of the class these methods are useful for utility functions that operate independently of class functions the behavior of the this keyword in different context was examined especially it can vary depending on the scope and the manner in which functions are called private members using symbols the use of ESX symbols as a way to somewhat hide implementation details was covered symbols provide a way to create properties that are not easily accessible from outside the class private members using weak Maps we discuss using weak maps to securely store private data for objects providing true encapsulation by ensuring that these details are inaccessible from outside the class and are eligible for garbage collection when no longer needed Getters and Setters the implementation and benefits of Getters and Setters were explored these are used to control access to the properties of an object allowing for validation logging and other side effects when properties are access or modified inheritance we covered how classes can inherit from other classes allowing for shared Behavior or across different types of objects and reducing code redundancy method overwriting the ability to override inherited methods was demonstrated showing how subclasses can modify or extend the behavior of methods defined by their super classes this section aimed to deepen your understanding of modern JavaScript features and best practices enhancing your ability to write clean maintainable and efficient JavaScript code in a professional development [Music] environment as app grow in size and complexity managing all the code in a single file becomes impractical and hard to maintain to address this issue it’s beneficial to split the code into multiple smaller files each encapsulating a specific functionality or feature these smaller files are called modules let’s go over the benefits of modularity the first benefit is maintainability smaller modular files are easier to understand debug and test the second benefit is code reuse modules can be reused across different parts of an application or even in different projects reducing code duplication the third benefit is abstraction modules allow developers to hide implementation details while exposing a clear interface making it easier to interact with the code practical implementation imagine you have a programmer class and its related functionalities divided across multiple modules for better organization you would place the programmer base class in its own file and for example the frontend program class in a separate file as these classes grow and gain more methods and enhance functionality managing them becomes easier since each class is in its own file or in other words its own module module systems in JavaScript historically JavaScript did not support modules natively and various Solutions were developed one of them being AMD which stands for a synchronous module definition this was primarily used in browsers and this format allows modules to be loaded asynchronously another module system is commonjs this is used in node.js and this format is designed for server side development another module system is UMD which stands for Universal module definition this combines the approaches of AMD and commonjs making modules usable in both the browser and node.js environments es6 modules with the introduction of es6 javasript now natively supports modules in the browser this system uses Import and Export statements to handle dependencies this course will cover commonjs for serers side applications and ESX modules for browser based JavaScript providing you with the skills to work flexibly with JavaScript in multiple environments in conclusion understanding and using modules and JavaScript not only improves the structure and maintainability of your code but also enhances its scalability and reusability by adopting modern JavaScript module standards like es6 modules and commonjs you ensure that your applications are robust maintainable and ready for growth what are the key benefits of using modularity in JavaScript applications and how do modules improve maintainability reuse and abstraction the key benefits of using modularity and JavaScript applications include maintainability this leads to smaller modular files that are easier to understand debug and test the second benefit is code reuse modules can be reused across different parts of an application or in different projects reducing code duplication the third benefit is abstraction modules allow developers to hide implementation details while exposing a clear interface making it easier to interact with The Code by organizing code into modules you make the application more manageable enhance its scalability and improve overall code quality how do commonjs and es6 modules differ and why is it important to understand both for developing JavaScript applications in various environments commonjs and es6 modules differ primarily in their usage and syntax with commonjs it is used in node.js for serers side development and it uses the require function to import modules and module. exort to export them with es6 modules this is supported natively in browsers and it uses Import and Export statements to manage dependencies understanding both is important because it allows you to work flexibly across different JavaScript environments using commonjs for Server applications and es6 modules for browser based applications ensuring compatibility and leveraging the strength of each module [Music] system modularity is a fundamental Concept in software architecture that helps organize code in a way that enhances maintainability reusability and scalability let’s apply these principles using the programmer class in a node.js environment so let’s consider the principle of cohesion cohesion refers to how closely related and focused the responsibilities of a single module are high cohesion within modules often leads to better code maintainability and understanding in the context of node.js you can create a module for the programmer class so each module and node.js has its own scope and anything defined in the module is private unless it is explicitly exported so let’s create new folder and I’ll name this undor nodejs now within it I’ll create a new file and I’ll name this programmer. JS So within it I can Define the programmer class so I’ll say class programmer Define my Constructor function so it takes in a name and the preferred language of the programmer so I’ll say this.n name and this. language now Implement a simple method for code which is just console log I’ll say this.name is programming in this. language and that with a period so now this class is only accessible within this file so within this module so we want to export it so a comment export the programmer class as the modules default export so in order to make this class available in other files I can say module. exports and will assign it to the programmer class so by doing this this makes this class the default export now I could also put it inside a JavaScript object and by doing this it now becomes a named export rather than a default export so I’ll undo that with command Z so now using the programmer module in another file I’ll create index.js and I want to utilize the programmer class in this file so I need to import that so I can do cons programmer and I will use the buil-in require function and pass in a relative path to where the programmer class is or the programmer module is so be4 slash meaning the current directory and the name of the file which will be program I can end that with a semicolon so now I can create an instance of a programmer so I can say const I’ll say Steven equals new programmer passing in my name and the preferred language of JavaScript and I can call step. code so the importation here utilizes the require function provided by Common JS in nodejs so nodejs refers to serers side environments so let’s bring up the integrated terminal and I’ll navigate to node.js and I will run the index file so node index.js and here we see outputs what we expected as the console statement so I log here the console statement defined in the code method so this was achieved through a default export now if I were to use a named export right so I put it inside a JavaScript object and save that in order to utilize this I would need to destructure it put it within curly braces now if I bring up the integrated terminal up arrow and run it again we get the expected result but in this case since we are just exporting one class it makes more sense to make it a default exporter clean this up the command D so encapsulation and privacy by structuring your application into modules and only exporting what is necessary you enhance encapsulation for example if there were private methods or properties within the programmer class these would not be accessible to Consumers of the programmer module who only receive what is explicitly exported so the encapsulation ensures that only the intended public interface of the programmer class is exposed and use in inclusion this lesson highlights the importance of modularity in software development particularly in node.js using commonjs modules by organizing code into cohesive modules and properly managing exports developers can create maintainable reusable and scalable applications the modular approach not only supports good software design principles but also ensures that each part of the application can evolve independently why is H cohesion important in software modules and how does it contribute to the maintainability and understandability of the code High cohesion in software modules means that the functions and responsibilities within a module are closely related and focus on a specific task this is important for two main reasons the first being maintainability modules with high cohesion are easier to update and debug since changes are localized to specific area with related functionality this reduces the risk of introducing errors elsewhere in the system the second reason is understandability high cohesion makes the code more intuitive and easier to understand when a module has a single well-defined purpose developers can quickly grasp what it does and how it works without needing to sift through unrelated code in summary High cohesion leads to more organized manageable and comprehensible code making the development process smoother and more efficient explain the concept concept of encapsulation in the context of modular programming how does using modules and node.js enhance encapsulation and what are the benefits of this approach encapsulation and modular programming refers to the practice of keeping a module’s internal details private and only exposing a limited necessary interface to other parts of the application and node.js using modules enhances encapsulation by scope isolation each module has its own scope meaning its variables and functions are not accessible outside unless explicitly exported by only exporting necessary parts of a module you control what other parts of the application can interact with reducing the risk of unintended interference and misuse now there are three main benefits the first is improv security sensitive or complex logic is hidden preventing unauthorized access and potential misuse the second benefit is the ease of Maintenance encapsulated modules can be updated or refactored independently without affecting other parts of the application and the third benefit is clear interfaces while defined interfaces make the system easier to understand and use promoting better code organization and collaboration in summary encapsulation via modules and no. JS leads to safer more maintainable and better organized code what is the Syntax for exporting a class or function as the default export in a commonjs module and how do you import and use this default ort in another file in commonjs to export a class or function as the default export you use module. exports to import and use this default export in another file you use the require [Music] function so for your exercise create a file named grocery item. JS and Implement a grocery item class with the properties of name and quantity then Implement a display method export that file or module and utilize it in index.js so for your exercise here in the node.js directory I’ll create a file and I’ll name it grocery item. JS So within it I’ll implement this class so it’s class grocery item then our Constructor so it’ll take in a name and quantity so I’ll assign these properties for the name and for the quantity and then we’ll have a display method so log and then tab back tick so I’ll say the interpolation of this.name times this. quantity so I implemented this simple class and now I want to export it so that I can import this class and utilize it elsewhere so module. exorts and I’ll make it a default export assign this to the grocer item class and so this enables me to import and utilize this class in other files so in the same directory I will create a file index.js and I will use the commonjs syntax to import it so I’ll say and the name of that export is grocery item assign to and I use the buil-in require function in commonjs and the directory is grocery item so now I can utilize this class grocery item as if it was defined in this file so I can say cons item new grocery item so the first parameter it accepts is name so I’ll say Apple apples as the the argument and for the quantity I’ll say four so now I want to call item. display let’s bring up the integrated terminal so I’ll do command J it’ll be control J on Windows and I will navigate to this file so I’ll run node index.js and here I get the expected output so let’s cover modularizing the programmer class using es6 modules in the previous lesson we use commonjs modules in order to Import and Export modules in serers side environments using node.js so with es6 modules this provides a modern and cleaner syntax in order to achieve the same thing for JavaScript files that run in web browsers so consider the scenario we want to ensure that certain properties of our programmer class such as skills are kept private and managed through a weak map we’ll separate the concerns into two modes one for the week map and the other for the programmer class itself so here in our directory _ practice I’ll create a new file and I’ll name this programmer skills. JS so this module will maintain a weak map to store private data related to programmers so let’s create that week map structure so programmer skills is assigned to a new week map so now we’ll create a function so I’ll name the set skills this will accept two parameters so a programmer object and the skills and we will just update the week map so it be programmer skills. set so the first parameter that we need to pass is the key so that would be the programmer object or instance and then the value so that will be the skills so now we’ll create another function for retrieving the value so we’ll name this get skills this accepts one parameter which will be the programmer and we’ll use that as the key in order to return the value so programmer skills. getet and then programmer as the argument so these functions are only available within this file so if we were to use commonjs syntax in order to export these two functions so we can use it elsewhere in our program we need to do module. exorts then a JavaScript object and specify set skills and get skills but with es6 modules we have a cleaner syntax to accomplish the same thing so we can remove this and just use the export statement so now both these functions are available to be used in other files so let’s create another file in our undor practice directory and I’ll name this programmer. JS so this module defines the programmer class and imports the functionality from programmer skills to manage skills privately so we use es6 module syntax to import those two functions so I’ll use the keyword of import and then curly braces set skills and get skills now we use curly braces because we are destructuring it so we use the from keyword and then we’ll specify the path to the file so it’s for slash for the current directory and then programmer skills. JS so now we can utilize these two functions in our class so it’ll be class programmer we’ll Define our Constructor function this accepts two parameters so the name and the skills so now let’s assign the name property and let’s utilize that function in order to set the skills and manage it privately so the first argument will be the this keyword meaning this current programmer object and the value will be these skills so let’s define another method I’ll name this code so this will log so Tab and then back ticks this.name is coding in then we’ll utilize the get skills function that we imported and pass into this keyword so this current programmer object so once again we will use the export keyword which is provided in es6 modules and we’ll utilize this in our index.js file so once again we use our import statement import the programmer from programmer. JS so let’s create an instance of this object I’ll say Dev new programmer the name of Steven and the skills of JavaScript so now we will call the code method so now in order to utilize ESX modules and have it executed in our web browser we need to update this script tag so instead of the type being text/javascript we’ll update this to be module so it’s treated as es6 module so let’s start live server so we’ll bring up the command pet with command shift andp then it’s live server open with live server and then we can inspect let’s go to our console and let’s resize this so here we see our expected output when we call the code method which is Steven is coding in JavaScript so another thing I want to show here in our program rjs file we exported our programmer class but we could also make this a default export so rather than using the export statement here I’ll remove that and I can say export default programmer so now when we go to our index.js file because it is a default export I can remove the curly braces and save it let’s see our output and here we see actually let’s clear against just so make it more easily viewable I can save it again and I get our expected output so this shows how we can use es6 modules in order to organize our code so as our applications grow in size we want to split up our functionality into different files so let’s cover some key points the first is modularity and privacy by separating the programmer class and its skills management into different modules we keep implementation details hidden and only expose what is necessary through exports es6 modules using Import and Export statements we can clearly Define dependencies and how modules interact this approach is cleaner and more maintainable than older module systems webpack and browser modules while modern browsers understand es6 modules natively complex applications might benefit from tools like webpack for abundantly modules managing dependencies and optimizing load times in conclusion this setup illust rates how to effectively use JavaScript modules to encapsulate logic manage privacy and expose a clean public API this modular approach not only AIDS in code organization but also enhances security and scalability and web development [Music] projects how do es6 modules enhance code maintainability and organization compared to older module systems es6 modules improve maintainability by providing a clear structure for defining and managing dependencies with Import and Export statements this helps keep the code organized and easier to manage what are the benefits of using tools like weback in conjunction with es6 modules for modern web development using tools like webpack with es6 modules helps bundle and optimize code managing dependencies more efficiently this improves load times and ensures that all necessary modules are correctly included making the development process smoother and the application [Music] faster so for your exercise use the es6 module syntax and create a file named grocery item. JS and Implement a grocery item class with the properties of name and quantity then Implement a display method export that file and utilize it in index.js so you imp imped this exercise previously and you use the commonjs module syntax in a node.js environment but in this case you implement these files and utilize it in a web browser so to implement this in the directory undor practice is where I have my index HTML file so I’ll create a new file grocery item. JS so I didn’t implement this in the previous lesson so to help us save time I’ll just copy this and I’ll paste it in here but currently I’m using the commonjs syntax but instead I want to use the es6 module syntax so I’ll make the grocery item class a default export so I can do that with export default and then grocery item so now I can import this in my index.js file so I’ll use the keyword import and then grocery item from grocery item. JS so now let’s create a new item equals new grocery item of bananas bananas and a quantity of five then I will call item. display and I will save it let’s resize this so we can see the web browser close the sidebar with command B and here I see the expected output of bananas times 5 in the landscape of modern JavaScript development especially when building browser applications the roles of transpilers and bundlers are crucial these tools help manage and adapt code for various environments ensuring compatibility and efficiency trans filers a trans filer is a type of tool that transforms source code written in one program language or version like modern JavaScript es6 into another version they may be more compatible with current environments such as older JavaScript es5 the old browsers can understand a popular transpiler is Babel one of the most widely used transpilers it allows developers to write modern JavaScript while ensuring that the code runs smoothly in environments that only support older standards for instance features like classes the let keyword the cons keyword Arrow functions and template literals introduced in es6 are not universally supported in older browsers so suppose you have a programmer class defined with modern JavaScript features using Babel this can be transpiled to be compatible with environments that do not support the latest JavaScript syntax now let’s consider bundlers a bundler Aggregates all the modules in your project and sometimes their dependencies into a single file or a few files this process is crucial for optimizing load times and managing resources efficiently a popular bundler is webpack webpack is the most popular bundler in the modern web development toolkit webpack not only bundles files but also minifies code and provides optimization like tree shaking which refers to removing unused code so an example with webpack you can configure webpack to bundle your JavaScript modules including the programmer class module into a single file this bundled file is then included in your web application ensuring that all script dependencies are resolved and manage efficiently so why would you use these tools well one reason is compatibility it ensures that modern code Works in environments that are not up to date with the latest ecmascript standards the second reason is performance it reduces the size of the code and the number of server requests required to load your application and third is for development efficiency it simplifies development by allowing you to use modern JavaScript features without worrying about browser compatibility while these tools are essential for browser applications due to their varied support for JavaScript standards across browsers nodejs environments generally do not require such tools for running JavaScript code AS no. JS is typically up to date with the latest JavaScript features however bundlers like webpack might still be used in nodejs applications for optimizing the application deployment in conclusion understanding and utilizing transpilers like Babble and bundlers like webpack is essential for any modern web developer looking to create efficient maintainable and compatible web applications they are especially important when the application needs to be scaled or maintain across different browser environments what is the primary function of a transpiler in modern javascrip development and why is it important the primary function of a transpiler in modern JavaScript development is to convert code written into newer versions of JavaScript like es6 plus into older versions like es5 that is compatible with a wider range of environments including older browsers this is important because it ensures that modern JavaScript features can be used by developers without worrying about compatibility issues allowing the code to run smoothly across all browsers how does bble help in making modern JavaScript features compatible with older browsers Babble helps make modern JavaScript features compatible with older browsers by converting newer JavaScript syntax and features like classes the let keyword the cons keyword and arrow functions into older syntax the all browsers can understand this process called transpiling ensures that code written with the latest JavaScript standards can run on any browser regardless of its version what role does a bundler like webpack play an optimizing web application performance and Resource Management a bundler like webpack optimizes web application performance and resource management by combining all your JavaScript modules and their dependencies into a single file or a few files it also minifies the code and removes unused Parts by utilizing tree shaking which reduces the file size and the number of server requests needed to load the application this leads to faster load times and more efficient resource usage why might nodejs applications generally not require transpilers like Babble but still benefit from using bundlers like webpack node.js applications generally do not require transpilers like Babel because node.js often supports the latest JavaScript features however it can still benefit from using bundlers like webpack to optimize performance by combining multiple files into one reducing file size through minification and managing dependencies more efficiently this makes the application faster and easier to deploy so let’s set up our JavaScript development environment so first we will cover installing essential tools with mpm before you start ensure that nodejs is installed on your machine as it comes with mpm which stands for node package manager this tool is crucial for managing ing third party libraries and development tools with mpm we can install open source packages to utilize in our projects so let’s open up the integrated terminal I can do that with command J or control J from Windows so ensure that no JS is properly installed by checking its version in the terminal I can do that with node DV and here I see I have version 20.1 16.0 so now let’s create a new directory for our project and we will navigate to it so rather than clicking on this icon I can just do that through the command line so I’ll do mkd for making a new directory and I’ll name it es6 actually I’ll name it underscore es6 hyphen tooling now I specified the underscore so that this directory shows up first when I view my project files in vs code so now let’s change directory into that new folder that we created so now we will create a package.json file so first let’s cover what Json is Json stands for JavaScript object notation and it is a lightweight data interchange format that is easy for us to read and write and easy for machines to parse and generate it is often used to transmit data between a server and web applications serving as an alternative to XML XML standing for extensible markup language so J Json is a more modern way to do this Json data is structured as key value pairs within curly braces and supports nested objects and arrays so let’s run the following command to create a package.json file in this new directory that we created and this file will help us manage all of our projects dependencies and other configuration so I’ll run mpm and then the keyword in it and then D- yes to accept all the default settings so after I run this this creates a new file named package.json to help manage by mpm dependencies so I can close this so here I see it is just a JavaScript object containing properties so now let’s focus on setting up Babble so this is to transpile Modern JavaScript and es6 plus to Backward Compatible JavaScript like es5 and we will use Babble to accomplish this so let’s clear this out so step one is is we want to install the necessary Babel packages you could also reference the documentation at Babel SL usage so now let’s install the necessary Babel packages using mpm these include Babel CLI Babel core and a preset package Babel preset environment which includes all the latest ecmascript features so we can do that with mpm install then app at Babble SL CLI then at Babble SL at Babble slash preset environment and we will specify a flag for Save Dev so it’s two hyphens save hyphen and then Dev and so what this does is that this installs the packages as developer dependencies so let’s discuss what these packages stand for so Babel CLI this provides the Babel command line interface for running Babel from the command line so Babel core this contains the core functionality of the Babel transpiler and Babel preset
environment this includes plugins to enable Transformations for all modern JavaScript features so let’s run this so our packages have been installed successfully so I’ll do command K to clear this and then command D to close it and here we see our three developer dependencies have been installed and they are now listed in our package Json file so now we need to configure Babble so we want to update our scripts here so our scripts determine different command line scripts that we can run so I’ll add comma and I will name this script Babble so the value will be what command we want to run which will be Babble then index.js which will be our project file and we’ll specify the output with- o and it will be in the build directory SL index.js so let’s create a build directory in here so it be build and let’s create another file index.js so here we replace our es6 JavaScript and after transpiling it the result will be stored in the build directory so we also need to add a file and it will be period Babel RC so if you’re fixing it with a period this means that this is a hidden file so Babel RC is a configuration file used by Babel which is a JavaScript compiler to specify options and presets for transforming your JavaScript code the name Babel RC stands for Babble resource configuration so we just Define this object here so the key will be presets and the value will be an array with the string add babble /pret environment we can save that so let’s go back to our index.js file and let’s write code es6 which uses modern features so I’ll specify a class and I’ll name it programmer I’ll Define a public field so I’ll say the role of the programmer and we just assign this to developer that will Define a private field this is a modern syntax and I’ll name it experience so now let’s define our Constructor function this takes in the name this takes in the technology they work with and I’ll say experience so we will set the name we can set the technology they work with and let’s set the private field of experience so assign this to experience let’s fine I’ll close the sidebar so we can see the code better so command B I’ll name it develop and then this will log out back tick this.name develops software using this. technology with this. experience this is actually a private so I need to pass for it years of experience so we can save that and I have another method which is get experience for accessing this private field and this will return this uh experience and also we will export it so we use that export keyword so here we see this class is using the modern features of having a private field but this language feature is not supported in JavaScript es5 so that’s why we need Babble to transpile this index JS file to es5 syntax so let’s navigate again to our package Json and we have the script that we Define and so we can execute this from the command line and it will run this command specified here as the value so let’s bring up with command J or control J and I’ll run mpm run and then the name of the script which is Babel so here in our output if we view the build directory the result of transpiling this modern es6 code can be found here and this is the result of using Babble so this code is now usable for browsers that only support older versions of JavaScript so now let’s cover integrating webpack for more efficient builds while B is excellent for single files webpack is more suitable when your project consists of multiple files as it bundles all your Project’s JavaScript into one or few files webpack will Minify both your code and the final bundles to reduce file sizes minifying JavaScript code involves removing unnecessary characters like spaces comments and line breaks to reduce file size and improve load times without changing its functionality so step one for setting up webpack you will install webpack and configure it to work with Babble to handle the entire project not just individual files and second we can automate with mpm scripts so we now navigate back to package.json we will update package.json to include a script that runs webpack ensuring all your JavaScript files are processed through Babel and bundled correctly we will cover this in the next lesson so in conclusion by following these steps you set up a modern JavaScript development environment capable of handling es6 plus syntax and producing code compatible with older browsers this setup ensures that your development process is efficient and your applications are robust and maintainable [Music] what command do you use to initialize a new mpm project and what file does it create to initialize a new mpm project use the command mpm in it– yes this command creates a file named package.json which manages your Project’s dependencies and configuration why is Babel use in a JavaScript development environment and what does it transform Babble was used in a JavaScript development environment to convert modern JavaScript code so this refers to es6 and newer into an older version so this is es5 that can run in any browser this ensures that new features and syntax can be used without worrying about browser compatibility what is the purpose of the Babel RC file and how is it typically structured the purpose of the babble RC file is to configure Babel specifying how JavaScript code should be transformed it is structured in Json format and usually contains an object with properties like presets and plugins that Define which transformations to apply webpack is a powerful tool that bundles JavaScript files into a single file optimizing load times and simplifying deployments webpack is a very large topic and it’s a very configurable technology so this course lesson will just scratch the surface of his capabilities so that you are familiar with it and you can explore the documentation at web pack.jpg file or a smaller amount of files so Babel on the other hand transpiles modern JavaScript so es 2015 or newer into backwards compatible versions so that our code can successfully run on older browsers and while in development we can still utilize the newest language features in syntax of modern JavaScript so let’s continue with the project that we were working on in our previous lesson let’s bring up the integrated terminal with command J or control J and we’ll run MC TM install and we’ll install the package of webpack webpack CLI Val loader will specify the flag of save Dev and– Legacy pure dependency SS package web pack is a powerful module bundler for JavaScript applications it takes modules with dependencies and generates static assets representing those modules so webpack CLI this is a command L interface for webpack it provides commands to initialize run and configure webpack from the terminal so this package Babel loader this is a webpack loader that allows Babel to transpile JavaScript files it converts modern JavaScript code so es6 and newer into backwards compatible versions so es5 using Babble in this flag Legacy period dependencies this tells mpm to use an older algorithm for resolving peer dependencies which can help bypass conflict so we’ll install this so successfully installed we can view our package.json and here we see these packages have been added to our developer dependencies so now let’s create a webpack doc config.js file so we’re going to right click webpack doc config.js so it is not mandatory to provide a custom configuration file for webpack as it does have a default convention before this course we’ll create a simple configuration file so we want to use the commonjs module syntax to import a library so that’s path require and then path and then we would do module. exorts assign this to a JavaScript object and here we will Define our configuration so we can specify the mode so for now it’s just development we’ll Define the entry point of our application so we’ll say that is in source and then index.js and we will Define the output so after webpack bundles everything where will it Place those files so we’ll specify the path and here we will use this path that we imported and so what this will do is this will create an absolute file path to where we want the output to be so there’s a keyword so that’s two underscores and directory name and we’ll specify the name of the directory to be disc for distribution so with this configuration we’re basically telling weback after you bundle all of our files and Minify our code Place everything in a directory named disc and we’ll specify the file name of the output and OB be main.js so now we use module we will Define some rules because we want to utilize Babel so this actually an array let’s update that so now it’s the object and then test so it’s a regular expression of for slash 10 back SL period to escape it JS a dollar sign and then another forward slash so basically we’re telling webpack every JavaScript file or every file that ends with the JavaScript extension we can say exclude node modules so the node modules directory so we don’t want to include the dependencies and we can say use and we want to utilize Babel to transpile our es6 code into backwards compatible es5 code so we can save this so this is our custom configuration don’t worry about memorizing all this this is just to demonstrate what web pack is so you have more insight so here we Define the entry point of our application to be in the source directory in the index.js file but currently our index.js file is at the root of the project so let’s create a new directory and I’ll name it source and this will contain our source code so I will copy this into that directory so I’m going instance of this programmer class so I’m going to say cons Dev new programmer say the name of Steven the technology of JavaScript and the experience I’ll say 10 and I will call the develop method now let’s go to our package Json file we wanted to find another script so that we can utilize web pack so I will name the key to be build and the value to be webpack so last thing I want to do is I want to create an index HTML file so index.html at the root of the project so exclamation point and then tab and I just want to create a simple H1 tag and I’ll say using web Haack I also want to specify a script tag so this will be in the distribution directory and the output will be main.js so now let’s bring up the integrated terminal with command and J and I’ll clear this out so we want to run our build script so we’re going to run webpack so mpm run build so webpack successfully bundled our code for our very simple project so here we specified our output directory to be disc for distribution and so this is the output that webpack generated to create backwards compatible code so once again it’s because this modern synex that we use is not compatible with older web browsers so we use Babel to trans file our code into es5 syntax and so webpack is used to bundle our code for production so this is a really simple example because we just have one file but you can imagine as our projects grow and we have hundreds of JavaScript files then weback comes a mandatory tool to optimize your code for production so here we can see what was generated now I can also update this so if I go to the webpack configuration file I specifi the mode to be development let’s change this to be production and I’ll bring up integrated terminal and let’s run the build command again so here we see the code has been minified so everything is placed on one line and all theace es and new lines have been removed to make the file size as small as possible this will help make our application faster once it’s running in a web browser so we can see this in action and actually see this in a browser so I’ll resize this and let’s open up the integrated terminal and I’ll do open and then period so this will open up finder on my Mac so now I’ll drag my index HTML file and drag it to my browser so let’s close this out so here in our index HTML file I have the H1 tag saying using webpack so we see that here and in our script tag this is referencing the production code that webpack and babble generated for us so this code and so the code that we were using in development was utilizing the programmer class with modern es6 syntax I created an instance of the programmer and called the develop method so it logged this out let’s check that it did that in our browser I can bring that up with doing the developer tools we drag that over here in our console we get our expected log statement view our sources and here we see the production code that webpack generated for us so I can close this so this is a very quick and brief overview of webpack just so you have a better understanding of what it does so in conclusion using webpack and babble together simplifies the process of modern JavaScript development by bundling and transpiling your code this stream line setup ensures compatibility across browsers and improves developer efficiency so for more detailed and advanced configuration refer to the webpack documentation at web [Music] pack.jpg and maintain code by breaking it into manag ible reusable pieces we covered commonjs so we explore commonjs which is a standard for modularizing JavaScript that allows the encapsulation of functionality into reusable packages which has been widely used in nodejs es6 modules this section covered es6 modules a native JavaScript feature that supports static Import and Export of code offering a more integrated and optimized way to handle modules directly in the browser or in node.js environments es6 tooling this topic address various tools and technologies that support es6 development enhancing code compatibility across different browsers and environments Babel we discuss Babel a JavaScript compiler that allows developers to write modern JavaScript code that is then transpiled into Backward Compatible versions for better support across all platforms webpack the lesson on webpack provided insights into how this powerful tool bundles JavaScript files and dependencies into a single file improving s speed and efficiency each topic was designed to equip you with the necessary skills to effectively use modern JavaScript tools and practices streamlining your development process and ensuring your projects are robust and [Music] maintainable node.js is an open- Source cross-platform runtime environment that enables the execution of JavaScript outside of a web browser it’s primarily used for building servers set applications and networking tools node.js supports the development of back-end Services commonly known as apis this stands for application programming interface these are essential for powering client applications such as web and mobile apps so key features of node.js one of the key features is its versatility and backend development node.js is suited for creating highly scalable data intensive and realtime applications its non-blocking event driven architecture allows it to handle numerous simultaneous connections with high throughput making an excellent choice for developing services like chat applications and online gaming servers a second feature is that it is quick to start and agile friendly nodejs is known for its ease of use and minimal setup enabling developers to quickly start building applications this attribute aligns well with Agile development practices where time to Market and adaptability are critical another feature is real word usage prominent companies such as PayPal Uber Netflix and Walmart leverage no. JS in their production environments these organizations have reported benefits such as reduceed development time decrease number of code lines and files which in turn contribute to enhanced performance in terms of request handling and response times another feature of node.js is that it enables you to use JavaScript for your backend and front end this allows developers to use the same language for both server side and client side scripts promoting skill reuse and reducing the learning curve for new Developers it provides a uniform programming language across the stack which leads to a clearer and more consistent code base njs also has a rich ecosystem nodejs benefits from a vast ecosystem of open- source libraries available through mpm which stands for node package manager which simplifies the addition of functionalities and accelerates the development process in conclusion nodejs is a popular choice for developers looking to build efficient and scalable web applications its ability to run JavaScript on the server side along with its robust tooling and supportive Community makes it a dependable and practical choice for modern web development what is node.js node.js is a runtime environment for executing JavaScript outside of a web [Music] browser so let’s go over understanding runtime environments a runtime environment is a setting where programs are executed it provides built-in libraries and manages the program’s execution offering various services such as handling IO or network request so JavaScript and web browsers historically JavaScript was primarily used within web browsers each browser comes with its own JavaScript engine which interprets and executes JavaScript code so Microsoft Edge uses the chakra engine the Firefox browser uses the spider monkey engine and Google Chrome uses uses the V8 engine these different engines can lead to variations in JavaScript Behavior across browsers within a browser JavaScript interacts with the document object model otherwise known as the Dom to manipulate web pages using methods like document. element by ID with the ID being root for this example the evolution to nodejs in 2009 Ryan do the creator of nodejs proposed an Innovative idea which was enabling JavaScript to run outside the web browser he leveraged Google Chrome’s V8 engine known for its speed and embedded it within a C++ program this integration birth node.js which is essentially an executable or aexe program that extends javascript’s capabilities Beyond web browsers so node.js does not have browser specific objects like the Dom because it is not intended for controlling webpage content instead it includes additional modules that provide JavaScript the ability to interact with the file system create servers handle networ protocols and more for example fs. read file can be used for reading files from the system and HTTP create server for creating a web server these functionalities demonstrate that node.js is equipped to handle backend Services making it ideal for building scalable Network applications what node.js is and is not node.js is not a programming language it uses JavaScript as its scripting language node.js is not a framework it does not impose any specific way way of organizing your project it merely provides a runtime environment with useful libraries node.js is a runtime environment it extends javascript’s reach to the server side offering tools and libraries that are not available in a browser context in conclusion nodejs revolutionized javascripts programming by expanding its scope from the client side in browsers to include serers side applications this advancement has made JavaScript a versatile powerful choice for full stack development node.js continues to thrive as a popular runtime environment due to its efficiency and the vast mpm ecosystem which provides numerous libraries and tools to enhance [Music] functionality node.js operates on a non-blocking asynchronous model which can be likened to a highly efficient restaurant service so let’s consider a restaurant analogy think of node.js like a single waiter serving multiple tables instead of waiting for one table’s meal to cook before taking another table’s order the waiter keeps taking orders and serving food as it becomes ready this demonstrates the asynchronous operations that node.js supports so now a technical explanation of this in node.js when a request is made the request is processed without blocking other operations nodejs does not wait for the database response but instead places a call back in the event Q which will be executed once the response is ready this allows the node server to handle other requests in the meantime contrasting this with synchronous operations in more traditional synchronous models like those used by Frameworks such as Ruby on Rails each request might be handled by one thread if the thread is busy it cannot take on more work this can lead to inefficiencies as other requests have to wait until free threads are available or additional Hardware resources must be provided synchronous operations have blocking Behavior in such synchronous environments a thread handling a database query will remain idle until the data is returned which is inefficient compared to nodes a synchronous approach so let’s go over the benefits of the node.js model the first benefit is efficiency node.js can handle numerous simultaneous operations on a single thread thanks to its event driven model this increases efficiency as the server can manage multiple tasks without waiting for any single task to complete the second benefit is scalability the ability to handle many requests on few threads allows node.js applications to scale effectively without requiring significant Hardware resources this is particularly beneficial for Io intensive applications such as web apis or real-time data processing and the third benefit is Resource Management nodes model promotes better resource utilization as the server remains active and non-idle even when data operations are pending let’s consider ideal use cases for nodejs node.js is well suited for applications that that require real-time data processing such as an online gaming application chat applications and live streaming services it excels in environments where the application needs to handle a large volume of short messages or commands that require low latency let’s consider the limitations of node.js node.js is less ideal for CPU intensive task for applications that require intensive data processing task such as video encoding image manipulation or large scale mathematical calculations no JS might not be the best choice its single thread in nature means CPU heavy tasks can block the entire system leading to delays and processing other concurrent operations in conclusion node.js leverages an asynchronous non-blocking model to provide efficient and scalable solutions for many modern web applications while it excels in handling iio operations it’s less suited for tasks that are heavily CPU bound understanding when and where to use node.js can help developers maximize their application perform performance and [Music] efficiency how does node js’s a synchronous non-blocking model improves server efficiency and scalability compared to traditional synchronous models no. js’s asynchronous non-blocking model improves server efficiency and scalability by allowing a single thread to handle multiple requests simultaneous L unlike traditional synchronous models where thread waits for a task like a database query to complete before moving on no JS processes requests without waiting it places task in an event queue and continues handling other operations this approach prevents idle waiting maximizes resource utilization and allows node.js servers to manage more requests with fewer Hardware resources making them highly efficient and scalable what types of applications are ideally suited for nodejs and what limitations should developers consider when choosing it for their projects node.js is ideally suited for applications that require realtime data processing and handle many simultaneous connections such as online gaming chat applications and live streaming services it excels in managing a large volume of short low latency messages however developer should consider its limitations for CPU intensive tasks like video encoding or large scale mathematical calculations no js’s single thread in nature can cause performance bottlenecks in such scenarios making it less suitable for applications requiring heavy data [Music] processing node jss module system is a powerful feature that allows developers to organize the code of large applications efficiently modules are discrete units of functionality that could be imported and used in other parts of a nodejs application or even across different nodejs applications so what are modules a module and node.js encapsulates related code into a single unit of functionality this could be anything from a library of utilities to a set of related functions that handle specific functionalities like database interactions file operations or network communications so why do we need modules modules are essential for several reasons one reason is maintainability by dividing applications into smaller manageable pieces modules make the code base easier to understand and maintain the second reason is reusability modules can be reused across different parts of an application or even in different projects which reduces code duplication and effort the third reason is namespace management using modules helps avoid Global namespace pollution by confining variables and functions within a local scope rather than cluttering the global scope so how do modules work in node.js in node.js each file is treated as a separate module node.js provides a simple and efficient way to create modules and expose them to other parts of your application so step one of creating a module you can create a module by placing the code into a separate Javascript file for example if you creating a utility module you might have a file named utility. JS so step two is exporting module contents node.js uses exports and module. exports to make functions and objects available to other files for instance if our utility. JS file contains a function to check if a number is prime you can export it like this so Implement a function I’ll name it is prime this accepts a number as a parameter so I’ll implement this if the number is less than equal to one return false if the number is equal to two return true since two is prime now if the number is divis by two then we return false let N initialize that to three we’ll take the square root of the number so don’t worry about memorizing this this is just to demonstrate so while n is less than equal to the Limit if the number is divisible by n then we know that it is not Prime so update the value by two only want to consider odd numbers otherwise it is prime so to make this function usable outside of this file or outside of this module we need to export it so we use the commonjs syntax module. exorts is prime so now let me create another file and I’ll name this index J so step three is importing a module so we use the require function to include the module in another file so I can say cons is prime then the requir function I’ll pass in a relative file path to the utility and save that utility. JS now I can utilize that and say log is prime I’ll pass the number of five let’s bring up the integrated terminal and I will run node index.js say we see the output of true because five is prime let’s do the value of six for example run it and here we see the value of false so this demonstrates how you would Implement a function export it and utilize it in another file so creating your own modules creating your own modules is as simple as writing any regular Javascript file and then using module. exports to expose parts of the module to other parts of your application you can expose objects functions or any JavaScript data structure in conclusion understanding how to effectively use the node.js module system is crucial for developing scalable and maintainable node.js applications by leveraging modules developers can create well organized modular code that enhances code quality and development [Music] efficiency how does the nodejs module system contribute to the maintainability and scalability of large applications the node.js module system contributes to maintainability and scalability by organizing code into smaller reusable units making it easier to manage understand and update individual parts of a large application without affecting the entire code base what advantages does the modular approach in node.js offer in terms of code organization and reuse across different projects the modular approach and node.js improves code organization by encapsulating functionality into separate units reducing complexity it also enhances code reuse allowing modules to be easily shared and used across different [Music] projects in nodejs Global objects are special objects that are available in all modules these objects provide essential functionality that could be access anywhere within a node.js application making them a fundamental part of the node.js runtime environment let’s cover the builtin global objects node.js comes with a set of predefined global objects that are readily available for use these objects serve various purposes from fundamental JavaScript objects to node specific objects that provide functionality unique to the nodejs environment the first one we will cover is the global object this is similar to the window object in browsers Global is the top level object in nodejs almost all other objects are either properties of this object or derived from it let’s consider the process global object this is one of the most important Global objects in node.js it provides information about and control over the current node.js process through process you can access environment information read environment variables communicate with the terminal or exit the current process the console global object this is used to print information to the standard out and standard err it acts similarly to the console object in browsers the buffer global object this is used to handle binary data directly it is built specifically for managing streams of binary data in node.js now let’s consider Global functions which consist of set immediate clear immediate set timeout clear timeout set interval and clear interval these globals are timer functions that help you schedule task to run after a specified duration or at a regular interval creating your own Global objects while node.js manages a variety of built-in globals developers can also Define their own Global variables that need to be accessible throughout the application here’s how to define and use custom Global objects and noj s Step One is defining a global object you can attach your custom Properties or objects to the global object this makes them accessible from anywhere in your nodejs application so we’ll use the global built-in object We’ll add a property and I’ll name this my config let’s assign this to a JavaScript object close it with a semicolon so we’ll add the property API URL we’ll just do a sample URL of https api. example.com we another property so at Port 3000 step two is using the global object once a property is attached to the global object it could be accessed in any module without requiring Imports or passing it explicitly so we can log this out we’ll do log and then tab for that keyboard shortcut then we’ll do global then that property we just Define which is my config API URL I’ll bring up the integrated terminal so I use the keyboard shortcut of command andj or control andj I’ve already navigated to where this file is in this directory so I’ll run node and I name this file five Global objects and here we get our expected value which is that API URL value that we added so caution when using Global objects while Global objects can be incredibly useful for sharing information across modules their use should be minimized due to the potential for creating tightly coupled components and the difficulty in tracking changes throughout the application it’s generally better to explicitly pass objects you need within modules through module exports and require statements in conclusion Global objects and node.js are powerful tools for developing applications which shared functionalities understanding both built-in and custom globals can help you effectively manage application-wide settings and maintain State across various parts of your application however limited use of globals is recommended to maintain a clean and manageable code [Music] base how to buil-in Global objects and nodejs facilitate application-wide functionality and control buil-in Global objects in node.js provide essential tools that can be accessed from anywhere in the application allowing for easy control and management of the node.js environment they enable functionalities like Process Management timing operations and handling binary data without needing to import or Define them explicitly in each module this makes them crucial for application-wide tasks and system level operations what are the potential risk of using custom Global objects and node.js and how can they be mitigated using Global objects and node.js can lead to tightly coupled code making it harder to track changes and debug issues globals are accessible everywhere so unexpected modifications can cause bugs that are difficult to trace to mitigate these issues it’s better to minimize the use of globals and and instead pass needed objects explicitly through module exports and imports this keeps the code base cleaner more modular and easier to maintain Global objects provide essential functions and variables that could be accessed from anywhere within a JavaScript environment whether in a browser or a node.js application let’s go over common Global functions the first one being console.log this is a global function that outputs to the console useful for debugging and logging application data second is set timeout this allows you to schedule a function to be executed after a specified delay this function is very handy for executing code after a pause clear timeout this is used to cancel a timeout previously established by calling set timeout set interval this schedule is a function to be run repeatedly at specified intervals this is useful for tasks like updating the UI at regular intervals clear interval this stops the repeated execution set using set interval so let’s cover Global scope in browsers in browser based JavaScript the global object is window all Global variables and functions are attached to this window object accessing globals when you declare a variable or function at the global level it’s accessible through the window object such as window. set timeout or window. message Global scope and node.js node.js does not have a window object because it does not run in a browser environment instead it uses a global object to provide a similar functionality so let’s discuss node.js globals in node.js you can access built-in modules and Global functions through the global object such as global. console.log or global. set timeout so an example of that we to do global. console.log this is a global console call and that with the semicolon now if we were to run let’s save this and execute it we get our expected console output now let’s call set timeout set timeout so the first argument to pass is a callback function so we’ll specify an errow function here so I’ll say log and then tab I’ll say this happens after a timeout now for the second argument for the set timeout Global function we specify the time in milliseconds so I’ll say a th so after 1 second we’ll execute this again we get our expected output and then after 1 second we see this console output so both of these set timeout and console.log are available globally so let’s further discuss variables and Global scope unlike in browsers if you declare a variable with the VAR keyword let keyword or cons keyword at the global level in node.js it does not attach to the global object this Behavior encapsulates the variables within the module scope avoiding unintentional conflicts so for example let’s comment this out fire do let message sign to follow world and then we log that out say global. message clear this out with command K up arrow and run it we see the value undefined so even though this message variable was defined at the global level it is not attached to the global object so it is enclosed within this file within this module so let’s cover an example using set interval and end interval so we can comment this out let’s define a function and I’ll name it update time so we’ll set the current date so new date and then we will log it out so back ticks to create a template literal I’ll say current time and then our dollar sign and curly braces now. two local daytime string so now we will WR a comment set an interval to run update time every second right so every thousand milliseconds I’ll say cons interval ID set interval and you want to call update time every second so this returns an interval ID which we will use to cancel it so we want to eventually stop the interval and we’ll do so after 5 seconds so we’ll call set timeout once again the first argument is a callback function so we’ll use our modern Arrow function syntax and after 5 Seconds we want to clear the interval to stop it and we need to pass the interval ID then we can log out interval cleared no more time updates now for the second argument we’ll pass in 5,000 for 5 seconds so let’s run this we’ll clear this out run it so shows the current time every second then after 5 Seconds we see interval cleared no more time updates so let’s discuss best practices while Global objects and functions are extremely useful you should limit their use reason being is you want to avoid polluting the global scope adding too many objects to the global scope can lead to conflicts and difficulties in maintaining the code it’s generally better to keep Global usage minimal second is you want to use local scope where possible you want to encapsulate variables and functions within a local scope such as within functions or module to avoid uned interactions and make the code easier to manage and debug in conclusion Global objects and functions are fundamental in both browser and node.js environments providing developers with powerful tools for performing common task understanding how to use these tools effectively and responsibly is crucial for developing robust [Music] applications how do Global objects differ in scope and behavior between browser based JavaScript and nodejs environments in browser based JavaScript the global object is the window object and Global variables and functions are attached to it and no. JS the global object is named Global but variables declared with the VAR keyword Le keyword or con keyword are not attached to it rather they are scoped to the module or in other words the file that they are defined in this difference helps prevent Global scope pollution at node.js making it easier to manage variables and avoid conflicts what are the best practices for using Global functions and variables in JavaScript to maintain code quality and avoid conflicts best practices for using Global functions and variables in JavaScript include minimizing their use to avoid polluting the global scope which can lead to conflict and difficult to maintain code instead encapsulate variables and functions within local Scopes such as functions or modules to keep your code organized and reduce the risk of unintended interactions this approach helps maintain code quality and makes debugging easier in JavaScript defining variables or functions directly in the globos scope is straightforward but can lead to complications and larger applications so let’s consider the global scope in browsers in a browser environment when you declare a function or a variable using the VAR keyword at the top level it is added to the global scope which means it is accessible through the window object so for example if you were to use VAR say hello and assign this to Anonymous function that logs out hello you can access it with window. say hello so that will successfully call the function now problems with global scope while convenient using the global scope can lead to several issues the first being namespace pollution the global namespace can become cluttered with too many variables and functions making it difficult to track down where specific things are defined the second problem is accidental overwriting if multiple parts of an application inadvertently use the global variable names they can overwrite each other leading to bugs that are hard to diagnose for example defining say hello in multiple files will cause the class loaded script to override all earlier definitions so for example in file one if we have VAR say hello set to Anonymous function and in file two we have a function with the same name so here if in file two if that is imported after file one then when we call say hello this will always log hello from File 2 regardless of expectations so the importance of modularity to mitigate the risk associated with global scope it’s essential to adopt modularity in your development approach so let’s cover modules and node.js in node.js every file is treated as a module and anything defined within that file is local to the module unless explicitly exported this encapsulation ensures that variables and functions do not inadvertently interfere with each other across different parts of an application the benefit is that it is private by default variables and functions are private to their module providing a clean namespace and preventing accidental interference and second is explicit exporting to make a function or variable available outside its module it must be explicitly exported adding a layer of control over what is exposed so for example in a node.js file we Define say hello assign this to an anonymous function log and then tab and we just log out hello to export it we use module. exports set to hello so we have to explicitly export it so this function can then be accessed in another file by importing it so we need to use the require function and then we can invoke it which we properly call the imported function so let’s cover the advantages of using modules the first is Clarity each module has a clear purpose in scope reducing complexity and enhancing readability the second Advantage is reusability modules can be reused across different parts of an application or even in different projects the third Advantage is maintainability changes in a module are localized impacting fewer parts of an application and thus reducing the risk of bugs in conclusion avoiding Global variables and embracing modularity is crucial in JavaScript development especially in larger applications or when working in a team environment by using modules developers can ensure their code is organized maintainable and less prone to unexpected behaviors caused by namespace pollution [Music] what challenges can arise from using the global scope in JavaScript especially in larger applications using the global scope in JavaScript can lead to several challenges and larger applications including namespace pollution where too many Global variables and functions make it hard to manage code and accidental overwriting where different parts of the appli unintentionally use these same Global names causing conflicts and bugs that are difficult to track down this can result in code that is harder to maintain and debug how does modularity in JavaScript help in maintaining clean and manageable code bases modularity and JavaScript helps maintain clean and manageable code bases by encapsulating code into self-contained units which we refer to as modules each module has its own scope reducing the risk of name collisions and accidental overrides this makes the code easier to understand debug and reuse as changes in one module are less likely to impact other parts of the application it also promotes better organization and Clarity leading to more maintainable and scalable [Music] applications so let’s go over creating and managing a module in node.js in this lesson we go through the process of creating a simple logging module in node.js this module will encapsulate all the functionality related to logging messages and can be reused in different parts of your application or even in other applications so setting up the logger module so let’s create the module file so here in this directory which I named loading a module so right click and I’ll name this logger JS so second we will add the functionality so we want to specify the functionality we want to encapsulate in this file otherwise referred to as a module con URL and assign to http my logger.log and we’ll Define a logging function we name it log the parameter it will accept will be a message so in a rle scenario you might send an HTTP request here but in our case we’re just going to log to the console and we’re going to log this message now this function as well as this constant is only accessible within this file or within this module so we want to make the module contents public so once again since variables and functions in a node.js module are private by default you need to explicitly export any data or functions you want to make available to other parts of your application so for exporting the functionality we would use module. exports to make the log function and the constant right this URL available outside the module so we would do module. exports and we can name this export log and assign this to this log function we also do module. exports do URL and set this to URL alternatively you could rename exports to provide a more intuitive interface to module consumers so rather than naming this URL we could rename this to be endpoint so let’s cover some best practices for exporting the first best practice is selective exporting in rro applications modules can contain numerous variables and functions it’s crucial to export only what is necessary to keep the module easy to use and understand this practice helps maintain a clean public interface the second best practice is the stability of the public interface the public interface of a module should be stable and not expose too many implementation details this this approach ensures that changes inside the module do not affect other parts of your application that depend on it so now let’s use the loger module I’ll create a new file in this directory and I’ll just name this index.js so here we need to import it so I’ll say const logger but I’ll name it I’ll use the requir function and I’ll use a relative path to where the logger file or logger module is and now we can call that so I’ll say logger log I’ll pass on the argument this is a message right so when we call logger.log I go back to logger JS you’re is calling this function which we exported and I’ll also log out so I’ll say log logger endpoint which is this constant that we defined and we named it endpoint when we exported it so let bring up the integrated terminal and I’ll run node index.js and we get our expected console log output so in conclusion by creating modules and node.js you encapsulate specific functionalities and expose a controlled interface to the rest of your application this modularity enhances code reuse simplifies maintenance and keeps your application organized when designing modules it’s essential to consider what should be private to maintain module inte integrity and what should be public to ensure [Music] usability what are the benefits of encapsulating functionality into modules When developing node.js applications encapsulating functionality into modules in node.js helps to organize code making it more manageable and reusable it allows developers to isolate specific functions or data reducing the risk of conflicts and making the codebase easier to maintain modules also enable better code reuse across different parts of an application or even in other projects leading to a more modular and scalable development approach how does careful management of a module’s public interface contribute to the maintainability and stability of a nodejs application careful management of a module’s public interface in node.js ensures that only necessary functions and variables are exposed keeping the internal implementation details hidden this reduces the risk of unintended interference with other parts of the application and makes it easier to update or refactor the module without breaking dependent code it contributes to the overall maintainability and ability of the application by providing a clear controlled and stable interface for other modules to interact with so let’s cover loading modules and node.js with the required function node.js uses the requir function to import modules which is a fundamental aspect of managing dependencies and modularity of your application this system differs from how scripts are loaded in your browser and is specific to the node.js environment so cover the basic usage of the requir function when you need to use functionality Define in another file or module you use require to load it so here are the steps of how it works Step One is loading a module so to load a module you pass the relative path of the Javascript file to the required function nodejs resolves the path and loads the module so for example you would have con logger this will be assigned to require and then you pass in/ logger so in this case the logger file is in the same directory or in other words the same folder node.js automatically assumes JS as the file extension if it’s not specified second is accessing exported members the requir function returns an object that represents the exported API of the module this object contains all the members that are exported from the module so if we were to do console. log and then logger this would output that function you can then use these members in your application like how we did logger.log and passing in the message best practices for using require the first best practice is using the cons keyword for requiring modules it’s a best practice to use the cons keyword as this prevents accidental reassignment of the module variable within your code which can lead to runtime errors so if we were to import that with con logger attempting to reassign a constant will result in an error helping catch mistakes during development so if we were to sign it for example to the number one this will throw an error if logger is declared with the con keyword the second best practice is utilizing tooling for code quality tools like JS hint can be used to scan your JavaScript code for potential errors and bad practices running JS hint on your code can help identify issues like improper use of variables before they cause problems at runtime so in your terminal you would run JS hint and the name of your file so in this case app.js this tool will report problems related to your usage of JavaScript potentially saving you from bugs that are difficult to diagnose exporting a single function sometimes you want to export a single function from a module rather than an object this can simplify the usage of the module where only one functionality is being provided so if we have our logger function we can do module. exports and assign that to the log function so we’re exporting just the function and then when we utilize that in your application file we import it with cons log and utilize the required function and then we can simply invoke it by just calling log and passing in the message as the argument in conclusion the required function in nodejs is essential for modular programming allowing you to include and use JavaScript files and modules efficiently by following best practices for module loading and leveraging code quality tools you can ensure your node.js applications are robust maintainable and airfree what role does the require function play and managing dependencies and modularity within a node.js application the required function in node.js is crucial for managing dependencies and modularity by allowing you to load and use code from other files or modules within your application it enables you to break your application into smaller reusable components making your code more organized maintainable and scalable by importing only the needed functionality require helps keep your application structure clear and modular how can following best practices when using the require function contribute to the maintainability and reliability of a node.js code base following best practices when using the required function and node.js such as using the cons keyword for module Imports and keeping modules small and focus helps maintain a clear and consistent code structure this reduces the risk of Errors makes your code easier to understand and improves its reliability it also prevents accidental reassignment of modules and ensures that changes in one part of the code don’t unintentionally affect other parts contributing to a more maintainable and robust code base so let’s go over how nodejs processes modules node.js has a unique way of handling JavaScript code which differs significantly from how scripts are executed in a browser environment so let’s discuss module wrapping in node.js when node.js executes a module it does not run the code directly as written instead it wraps the module code inside a function this approach is not immediately apparent to the developer but it is fundamental to how nodejs operates so here’s what happens under the hood first is function wrapping each module is wrapped in a function before it is executed the function wrapper helps to isolate module from the global scope which means variables and functions defined in a module do not pollute the global scope so just to show an example of what this might look like we have in parenthesis can we Define function exports then require module and we’ll discuss this more in detail in this lesson just want to demonstrate a visual example of what this will look like directory name then the function block so your module code lives here let me rename this lives here so we to do say Con X assigned to below then we can log this out so when we Define these two statements so cons X assigned to a string and then logging it out node.js will implicitly wrap this module code inside a function so second is the module wrapper the function that wraps each module takes several important parameters which we specified here so the first is exports this is used to export module functions and variables the second is requir a function used to import the exports of another module the third is module which represents the current module next is the file name so two underscores and then file name so this refers to the file name of the module and then directory name so third is exporting from modules you can add properties to exports or module. exports to make them accessible to other modules like in our previous example when we did module. exports. log and assign this to the log function or we can do exports. log assign to log however replacing exports entirely won’t affect module. exports because exports is just a reference to module to exports using built-in modules node.js comes with a variety of built-in modules that provide rich functionalities like file system manipulation HTTP server creation and handling system pass these modules are essential tools for node.js developers and are thoroughly documented in the node.js API documentation so an example of using a built-in module here to do cons path and then we require the path let’s comment this out now we can get the path object so I’ll say path object sign two path dot parse then pass in file name and let’s log this out path object bring up our integrated terminal we’ll run this file and here it outputs this object showing my current file so in conclusion understanding how node.js executes module code and utilizes function wrapping provides a clearer picture of the runtime environment this process ensures that Global variables and functions from one module do not interfere with another fostering a more organized and secure coding environment furthermore node.js built-in modules are powerful tools that extend the functionality of node applications enabling developers to handle a wide range of system level tasks [Music] efficiently how does node.js module wrapping mechanism contribute to isolating module scope and preventing Global namespace pollution no. js’s module wrapping mechanism isolates each module scope by wrapping the module code in a function this prevents variables and functions defined in one module from leaking into the global scope reducing the risk of naming conflicts and ensuring that each module operates independently this mechanism helps maintain a clean and organized code base where Global namespace pollution is minimized making the application more secure and easier to manage what benefits do node.js built-in modules provide for handling system level tasks and application development no. js’s built-in modules provide powerful tools for handling system level task such as file manipulation network communication and managing paths these modules save developers Time by offering ready to use optimized functionality that integrate seamlessly with the nodejs runtime by using these built-in modules developers can efficiently manage system resources build robust applications and avoid the need to reinvent common functionalities leading to more secure maintainable and performant [Music] applications so let’s go over retrieving system information with the node.js OS module When developing applications that require system level data node.js provides a built-in module called OS which allows you to gather information about the underlying operating system so let’s cover using the OS module step one is to import the module so at the very start of file we’ll say cons we name it OS require and the name of it is OS for operating system so step two is to retrieve memory information so the OS module provides several methods to get system information such as os. tootal memory and os. free memory which Returns the total and free memory of the system respectively so we can do that const I’ll say total memory os. total M and then free memory os. free memory let’s log this out so I’ll say log I’ll use back tis say total memory and then hold on memory and I’ll do shift option and down arrow to copy this I’ll say free memory and let’s just copy and paste it here so open up the integrated terminal so that’s command J so let’s run this file with node and then the name of the file so here I get the expected output so this provides insights that are not typically accessible from client side JavaScript code which runs in the browser so in conclusion the OS module is a powerful tool in node.js for accessing operating system level information this can be particularly useful for applications that need to monitor or manage system resources using node.js developers can write server side code that interacts directly with the operating system offering capabilities beyond what is possible in a browser environment this makes nodejs a great choice for building more complex system sensitive backend [Music] applications how can the nodejs OS module be utilized to gather essential system information for applications that require insights into the operating systems resources the node.js OS module can be utilized to gather essential system information by providing methods to access details like total and free memory CPU architecture network interfaces and more this information is crucial for the applications that need to monitor or optimize system resources especially in server environments we’re understanding the underlying operating system can help in managing performance and resource allocation effectively the OS module allows developers to write scripts that interact directly with the operating system offering insights that go beyond typical client side capabilities what advantages does nodejs offer for building resource sensitive backend applications that need to interact with the operating system directly nodejs offers several advantages for building resource sensitive backend applications that need to interact with the OS directly it provides built-in modules like the OS module which allows access to system level information such as memory usage CPU details and network interfaces this direct interaction with the OS enables better monitoring management and optimization of system resources additionally node. js’s non-blocking I model makes it well suited for handling multiple tasks efficiently which is critical in resource sensitive [Music] environments so let’s go over understanding the node.js file system module node.js provides a powerful built-in module called FS for interacting with the file system this module is essential for reading from and writing to files on the server so first you would import the fs module so at the top of your script you can do const FS require and the name of it is FS for file system now let’s discuss the methods in the fs module so the fs module includes a variety of methods to handle file operations which comes in two primary forms the first being synchronous which is blocking and asynchronous which is non-blocking so for the first form which is the synchronous methods synchronous methods block the execution of further JavaScript until the file operation completes they are straightforward to use but can significantly slow down your application especially under heavy load so an example of this could be cons files and then fs. read directory sync so the pass in the current directory we can do console.log files so this will log all files in the current directory let’s run this and integrate a terminal so it’s node and the name of this file so here we see all the files in my current directory I’ll clear this out with command and J now the second form is asynchronous methods asynchronous methods on the other hand perform operations in the background and accept a callback function that runs once the operation completes this approach is non-blocking and allows node.js to handle other tasks while waiting for the file operations to complete so an example of reading directories asynchronously below I can do pass and also say async files just to give a different name so fs. rir directory first argument is the current directory and then it takes in a callback function so I’ll specify that to be an errow function so eror and then files So within it if there is an error and I will simply console log it so erir and then else console. log will say the result files so this will log the files once it’s read so let’s comment this up for now and let’s see the output when we do so asynchronously so once again we get the same result outputting all the files in my current directory so best practices for using FS methods the first best practice is avoiding synchronous methods in production while synchronous methods are easy to use and understand they should generally be avoided in production especially for iey operations a nodejs process runs on a single thread and using synchronous methods can block This Thread leading to Performance bottlenecks when handling multiple requests the second best practice is to prefer asynchronous methods asynchronous methods allow your node.js server to remain responsive by freeing up the main main thread to handle other requests while waiting for file operations to complete this approach is crucial for maintaining performance and applications that serve many clients simultaneously exploring the documentation for a complete list of available methods and additional details visit the official node.js documentation for the fs module this documentation provides comprehensive insights and examples for both synchronous and asynchronous methods in conclusion understanding and utilizing in the fs module and node.js is crucial for performing file operations effectively by preferring asynchronous methods you can ensure that your node.js applications remain efficient and responsive underload making full use of node. js’s non-blocking architecture what are the benefits and drawbacks of using synchronous versus asynchronous methods when performing file operations in node.js synchronous methods in node.js are easy to implement and use but they block the execution of further code until the operation completes which can lead to Performance issues especially under heavy load a synchronous methods perform operations in the background without blocking the main thread allowing the server to handle other tasks simultaneously this makes them more suitable for production environments ensuring better performance and responsiveness the draw call back is that they require handling callbacks or promises which can add complexity to the code why is it important to prioritize a synchronous methods for file system operations in production environments when using node.js it is important to prioritize asynchronous methods for file system operations and node.js production environments because they allow the server to remain responsive by freeing up the main threat to handle other task asynchronous operations prevent the application from being blocked by long running task which is crucial for maintaining high performance and efficiently serving multiple client requests simultaneously this helps ensure the application can scale and handle High loads without performance bottleneck so let’s go over understanding events and nodejs node.js is built around an event driven architecture primarily using an event Loop mechanism which makes it efficient for Io heavy operations so the core concept of events and node.js and event signify something that has occurred within the application for example when a server receives a request at a port it’s an event the nodejs runtime handles this event by generating a response so let’s go over using the event emitter class event emitter is a core class in node.js used for handling events within your application so here’s how you can use it step one would be importing the event emitter so first you need to import the event emitter from the events module so name this event emitter and I’ll use Pascal naming convention the require function and then events so step two is creating an instance so event emitter is a class and you must create an instance of this class to use it so this instance will manage the events for your application so we’ll name our object emitter use our new keyword to instantiate the new object so step three is registering listeners listeners are functions that are called when a specific event is emitted so use the on method to register a listener for an event so we’ll do emitter then the method on so we’ll name the event so this will be message log then we pass in a callback function so I’ll use the modern errow function syntax and we’ll just log out to the console and I’ll say listener call and save that so step four is emitting events the emit method is used to trigger an event when this method is called all register listeners for the event are invoked so we can do emitter do Emit and then we’re using the same name of the event for this event to have occurred so so it’s important to register listeners before emitting the event as they will not be triggered retroactively so let’s bring up the integrated terminal and we’ll run this file so here we see when we emitted this event it called the event handler which we pass in as the second argument here so let’s discuss event arguments events can also pass data to their listeners and you can send multiple parameters to The Listener function by passing them as additional arguments to emit so here we currently have an empty parameter list but we can specify this to be ar for example so let’s include that in our console log statement say R now when we emit it we could pass in an object so I can say the ID is one and the URL is Sten cod.com so now this second argument that we pass will be the argument that our event listener or event handler receives so let’s call this again and here we see we successfully passed data to our event listener so let’s discuss the Practical usage event emitter is widely used in node.js core modules like handling HTTP requests and web servers or reading files asynchronously developers can use this pattern to handle custom events in their applications enhancing the modularity and separation of concerns in conclusion the event emitter class is a fundamental part of node.js that helps manage events and listeners facilitating the event driven architecture that nodejs is known for proper use of this class can help you build robust and maintainable node.js applications by organizing operations around the handling of various system and custom [Music] events how does no js’s event driven architecture enhance the efficiency of handling IO operations node js’s event driven architecture enhances the efficiency of handling IO operations by using an event Loop
to manage multiple tasks without blocking the main thread when an i operation is initiated node.js can continue processing other tasks while waiting for the operation to complete this non-blocking approach allows node.js to handle many concurrent operations efficiently this non-blocking approach allows node.js to handle many concurrent operations efficiently making it ideal for applications that require high performance and scalability and auto intensive environments what role does the event emitter class play in managing events and listeners within node.js applications the event mitter class in node.js plays a central role in managing events and listeners it allows you to create and handle custom events within your application by using event emitter you can Define events register listeners that respond to those events and emit the events when certain conditions are met this helps organize your application around an event driven architecture enabling more modular maintainable and responsive code especially in applications with a synchronous operations so let’s go over handling data with events and node.js when working with a node.js event and M class it’s common to send additional data about an event this can help listeners perform their tasks more effectively by providing them with the necessary context so let’s cover emitting events with data when triggering an event you can pass data as arguments to the emit method this data can be accessed by the event listeners so first we will cover passing multiple arguments while you can pass multiple arguments separately it is generally more manageable to encapsulate them in an object as we did in the previous lesson so I’m going make a copy of this so I’ll sh option and down arrow so in the previous example we passed all the data and capsulate within an object but we also can just pass them as an argument so passing in the ID value and the URL but this is less manageable as it has less context so we prefer to use an object because the name of the property indicates what this value represents so it’s not just a magic number right it has more context so by passing an object you can include multiple pieces of data under a single event argument which makes handling this data in listeners simpler and more organized let’s clear this out so now let’s cover registering listeners to handle data listeners can be set up to receive event data here’s how to define listeners to handle the data pass to them so using a function to listen for events you can Define listeners using either traditional function syntax or es6 Arrow functions both methods allow you to access the event data passed from the emit call so in the previous lesson we use es6 Arrow functions to copy this we could also used traditional function syntax so remove that arrow and this will work as well so in both cases the argument right so this parameter that we specified also commonly called event args or simply e represents the data object pass from the imit method so I remove this and we’ll stick with the more modern syntax so let’s go over a practical example which is a custom logging event so consider a scenario when you want to log custom messages so you can set up a specific event for logging messages and emit data related to those messages so let’s do we can comment this out since you don’t need that right now emitter Doon and we’ll name this event to be logging the pass in an eror function this accepts parameter of data and we’ll log out I’ll say receive message and we’ll do comma data. message so now we can emit a logging event with the message data so emitter emit so the name of this event which is logging we’ll pass in that data object which has a proper a message and I’ll just say hello so I’ll bring up the integrated terminal command J then the name of this file we run it with node and I get the expected console output when we call it emit for this event to occur so here the logging event is configured to pass an object containing a message and The Listener logs this message when the event is emitted so in conclusion using event emitter and nodejs to handle events with additional data is a powerful pattern for developing modular and responsive applications by encapsulating data in an object and passing it through events your application can maintain clear and manageable communication between different parts of your system this approach not only keeps your code organized but also enhances its flexibility and scalability how does passing data through events improve communication and modularity within a node.js application passing data through events in a nodejs application improves communication and modularity by allowing different parts of the application to interact efficiently it’s able to do so without direct dependencies it enables event listeners to receive relevant data when an event occurs promoting a clear separation of concerns this modular approach makes the code more organized flexible and easier to maintain as components can respond to events handle data independently what are the benefits of encapsulating event data in an object when using the node.js event M Class encapsulating event data in an object when using the node.js event emitter class provides several benefits it allows you to pass multiple related pieces of data as a single argument making the event handling code more organized and easier to manage this approach also enhances readability and scalability as the object structure can easily be extended to include additional data without altering the function signatures or logic it simplifies the communication between different parts of the application ensuring a cleaner and more modular [Music] design so let’s go over integrating event emitter into custom classes in Rob applications it’s uncommon to use event emitter directly instead you typically extend event em emitter in a custom class to encapsulate related functionalities along with event handling capabilities extending event emitter allows you to build self-contained components that can generate events and handle their own functionalities this is particularly useful for creating modules that need to perform actions and then notify other parts of your application that those actions have completed so we’ll go through the process of creating a logger class that extends event emitter to handle logging operations and emit events so Step One is defining the loger class we create a new directory and I’ll name this 15 custom class event emitter so in this directory I will create logo. JS let’s import event emitter this will be the base class that is from events so now we’ll Define our custom class which is lo ER and we want to extend the functionality CU logger is in an event emitter extends event emitter so it inherits all its functionality so now let’s define our log method the log takes in message as its parameter variable I a comment here and I’ll say logic to log and HTTP request or any message so do console.log of the message add another comment so I’ll say emitting an event when the log method is called so I’ll say this so This current object I’ll call emit since logger is an event emitter We inherited this emit method for to call or invoke an event this will call the event logged event and we’ll pass in the ID and the URL just say stepen craft.com just for example now once again this class is only available within this file or within this module so we need to explicitly export it so I’ll say module to exports on to logger so we’re exporting this class create a new file here and I’ll name it app.js and we want to utilize this logger class we just defined let’s import it so logger require it’s name logger I’ll instantiate it right so we’re creting a new instance of that log class that we defined a comment here and I’ll say registering a listener for the message log event right so we need to Define this event and listener before we call it right so we named it message logged so I’ll say logger do on message log for the second argument takes a callback function so we use the modern P6 errow function syntax log to the console and we will log out listener received an argument and now let’s actually call that log function so add a comment here I say calling the log method which will trigger the message logged event right so we’re calling this method that we Define here so I’ll say logger.log of not to say hello world let’s bring up the integrated terminal then I’ll navigate to this directory that I created with 15 custom and now I’ll run node app.js so here we see it logged out we go to the implementation of this it logged out the message which was hell world and then it logged out what we had in this event listener so listener received and then the data that we passed to it so let’s go over the benefits of this approach the first benefit is encapsulation the logger class encapsulates both the logging functionality and the event handling making it modular and easier to manage the second benefit is reusability by abstracting the event emitter Behavior into a class you can reuse and extend this class wherever needed without rewriting the event handling Logic the third benefit is maintainability having a dedicated class for logging and event emission helps maintain and modify logging Behavior independently from the rest of your application let’s go over a common mistake so a common mistake when starting with event emitter is to create multiple instances of the emitter when only one is needed or to bind listeners to different instances than the emitter that emits the event this is why encapsulating the event emitter within a class as shown ensures that the event listeners are correctly associated with the specific instances of the class that emits the events in conclusion by extending event emitter and custom classes like logger nodejs applications can handle complex functionalities while efficiently communicating events across different modules this pattern enhances the modular architecture of the application promoting clean and manageable code that aderes to Modern software design [Music] principles what are the advantages of integrating the event emitter class into custom classes when building modular components in node.js integrating the event emitter class into custom classes and node.js allows you to build modular components that can handle specific task and emit events related to those tasks this approach encapsulates functionality and event management within a single class making the code more organized reusable and easier to maintain it ensures that event handling is tightly coupled with the relevant functionality improving the overall architecture and communication between different parts of the application how does extending event emitter and custom classes enhance the reusability and maintainability of node.js applications extending event emitter in custom classes enhances reusability and maintainability by encapsulating both functionality and event management into a single self-contained mod modol this allows the class to be easily reused across different parts of an application or in other projects without duplicating code it also simplifies maintenance because the logic for emitting and handling events is centralized making it easier to update or modify without affecting the rest of the [Music] application so let’s cover creating a web server with no. JS node.js provides the HTTP module a powerful tool for developing networking applic such as web servers that listen for HTTP requests on a specified Port let’s cover the basic web server setup so the first step is to import the HTTP module the HTTP module includes the functionality necessary to create server instances so we can do cons HTTP require HTTP so the second step is to create a server use the create server method to create a new server the server can handle http requests and responses we do cont server assign to http create server step three is listening to events the server object created by HTTP create server is an instance of event emitter this means you can listen to events like connection for lower level Network events you can do server.on the event of connection and we’ll pass in our call back so the parameter will be socket and we’re using our modern es6 errow function syntax ended with the semar colon and for now we’ll just log to the console new connection and save that so step four is starting the server we’ll have the server listed on a port such as 3001 to handle incoming requests so we could do server. listen at 3001 and we’ll log out to the console listening on Port 3001 so now let’s run this and integrated a terminal so here we see it’s listing on P 3001 if we navigate to our web browser so now if I navigate to Local Host 3001 let’s resize this back in vs code we see it says new connection which is this console log statement here close this out and contrl C to stop this program so handling HTTP requests more efficiently while the above method works for simple demonstrations handling HTTP requests based on different routes can be done more effectively so step five would be refining the server to handle requests instead of listening to the connection event you can directly handle HTTP requests by providing a call back to create server that deals with request and responses so here where we called create server we pass in the call back function so the request and the response using our Arrow function syntax so if the request URL is at the index right so just a for slash we can do response. right hello world and who will end the response otherwise we can say if request URL is at API courses we can say response. right json. stringify we’ll just say an array of one two and three and response. end so let’s run this again up Arrow run so once again it’s listing on that Port you can navigate to it I’ll say Local Host 3001 and here we see hello world as specified and we did response. right now if we navigate to this path add this to the end and here we see this array that we specified here so this setup directly responds to http get requests at the root with the for slash as well as at API SL courses which sends a Json response in this case an array let’s close this with contr C close it out so using Express for complex applications for more complex web applications managing routes with the native HTTP module becomes cumbersome this is where Express a web application framework built on top of the HTTP module comes in handy so let’s discuss the advantages of Express the first being simplification of routing Express provides a much cleaner and organized way to handle different HTTP routes with minimal effort second Advantage is middleware support Express allows you to use middleware to respond to http requests handle errors and process data and third is enhanced server capabilities while Express uses the underlying HTTP module it simplifies many tasks and adds powerful new features and to discuss what an example of this might look like you need to utilize the express mpm module and create a package.json file after you import Express you can create an instance of of it by calling Express then you can Define the get request for both the root path as well as the API for/ courses path so in conclusion starting with node js’s HTTP module is great for learning the basics of network communications in JavaScript however for building more sophisticated applications such as a framework like Express can greatly simplify your code and enhance your server’s functionality making it easier to maintain and expand [Music] what are the benefits of using the node.js HTTP module to create a basic web server and when might you consider using a framework like Express instead using the node.js HTTP module to create a basic web server is beneficial for learning the fundamentals of network communication and handling HTTP requests directly it offers full control over the server’s Behavior with minimal overhead how however for more complex applications a framework like Express is preferable because it simplifies routing supports middleware and adds powerful features making the development process faster more organized and easier to maintain as the application grows how does the event driven nature of node.js influence the design and functionality of a web server created with the HTTP module the event nature of node.js influences the design and functionality of a web server by allowing it to handle multiple requests concurrently without blocking the main thread this non-blocking iio model ensures that the server can efficiently manage incoming connections and process requests as events responding to them asynchronously this design is particularly well suited for high performance applications where the server needs to remain responsive and scalable even under heavy load so let’s summarize what we covered for the node module system first we covered an introduction to nodejs this part of the course provides a foundational understanding of what node.js is and the benefits of using it then we cover node.js architecture we explain the internal architecture of node.js including its non-blocking event driven nature that allows for high performance across rward applications we did a deep dive into nodejs functionalities where we covered how node works so we learn more about the underlying Mech mechanisms that power node.js such as the event Loop and asynchronous programming we covered an introduction to the node module system where we discussed the modular structure of node.js applications emphasizing how modularity is achieved and managed we covered working with node.js modules which includes Global objects so this covers buil-in Global objects and node.js which are accessible across all modules covered modules and focus on the importance of modules and node.js for organizing and maintaining code we went through creat and loading modules we covered practical guidance on how to create your own modules and how to import existing ones module wrapper function this section covered how node.js wraps module code within a function to maintain module scope and privacy then we went through and covered specific nodejs modules starting with the path module so this introduces utilities for handling and transforming file paths the OS module which provides information about the computer’s operating system where the nodejs application is running the file system module so this demonstrated how to work with the file system for reading from and writing to files and the events module so we discussed the event emitter class and how to handle custom events and applications we went through more advanced Topics by covering event arguments which detailed how to pass and handle data with events using the event emitter then we extended the event emitter where we learn how we can enhance and customize the event emitter for more complex event handling scenarios lastly we covered the HTP module so this outlined how to to use node.js to create web servers and handle HTTP requests effectively in conclusion this section covered the fundamentals of how to use nodejs and its module system for building scalable and efficient applications by understanding and utilizing the core modules and Architectural principles of node.js developers can create robust backend services and applications suited for a variety of world world tasks [Music] in node.js development managing third-party libraries and modules is facilitated by package managers the two primary package managers used in the nodejs ecosystem are mpm which stands for node package manager and yarn so first let’s go over understanding mpm mpm is not only a package manager but also a registry that hosts a vast collection of free open source libraries these libraries can be easily integrated into your nodejs projects to add new functionalities let’s go over mpm Basics the registry visit npmjs.com to explore a wide range of packages available for various functionalities these packages are open source and free to use installation mpm comes bundled with node.js so when you install node.js you automatically get mpm installed on your system to check the version of mpm that you have installed in your system from the command line you can run mpmv So currently I have 10.8.2 installed on my system now to update mpm and to ensure that you have the latest features and security patches you can update mpm to a specific version globally using the following command so here I’m using a Mac so I’ll use the command sudu mpm install then the flag DG mpm at latest or enter my password this will update it so I use the latest version now we use mpm to install open source packages to add a package to your project you would use the command mpm install and then the name of the package so let’s discuss Global versus local installation by default mpm installs packages locally within your project however some tools need to be available globally to be run from anywhere on your system so you would do that with mpm install then use the flag – G and then the package name introduction to yarn yarn is another popular package manager that could be used as an alternative to mpm it was created by Facebook and is known for its speed reliability and improved Network performance installing yarn unlike mpm yarn is not bundled with no JS and must be installed separately you can install yarn globally using mpm so the command to install it is mpm install DG and then the package name which is yarn using yarn let’s cover how you can add a package with yarn similar to mpm you can add packages to your project with the command yarn add and then the name of the package why use yarn yarn caches every package it downloads so it never needs to download the same package again it also paralyzes operations to maximize resource utilization and thus install packages faster publishing your own package if you’ve developed a functionality that could benefit others you can publish your own packages to mpm making it available to the global node.js community so first you would prepare your package so ensure that your package is well documented has a clear readme file and includes all necessary metadata in your package.json file step two is publishing so you would run the commands mpm login after you loging with your credentials then you would run the command mpm publish in conclusion mpm and yarn are essential tools for any node.js developer they simplify the process of integrating thirdparty libraries into your projects manage independent effectively and helps you contribute back to the community by publishing your own packages whether you choose npm or yarn depends on your specific needs and preferences as both provide robust features to streamline development workflows what are the key differences between mpm and yarn in terms of speed reliability and package management features the key differences between mpm and yarn are speed reliability and package management so when covering speed yarn generally installs packages faster than mpm because it paralyzes operations and caches packages locally reducing the need for repeated downloads for reliability yarn ensures consistency by using a lock file which is named yarn. loock to keep track of exact package versions which helps avoid version mismatches so when considering package management yarn offers better off find support and more efficient dependency resolution while mpm is more integrated with the node.js ecosystem and its package registry how do package managers like mpm and yarn contribute to efficient dependency management and no. JS projects package managers like mpm and yarn contribute to efficient dependency management and node.js projects by automating the process of installing updating in organizing thirdparty libraries they manage versioning to ensure compatibility handle dependency trees to prevent conflicts and streamline workflows through commands for adding removing and updating packages both tools also maintain lock files to ensure consistent environments across different development setups making it easier to collaborate and maintain project stability so let’s cover setting up a node.js project with mpm when starting a new nodejs project one of the first steps is to set up a package.json file this file contains metadata about your project and manages the Project’s dependencies so let’s go over creating a new project directory I’ll open up the integrated terminal let’s expand this and we’ll create a new directory so mkd and I’ll name the directory mpm DDO we’ll change into that new directory now we will initialize our package Json file so before adding any node packages to your project you need to create a package.json file this file will track your project dependencies and store other important project information we’ll create this file by using the command mpm andit so mpm initialize so this command will prompt you to enter several pieces of information such as the Project’s name the version description the entry point such as an index.js file the test command repository keywords author and license so these details help Define and document your project so I have to say enter so the project name will be mpm demo the version is 1.0 the description I’ll say lesson on node package manager entrypoint index.js file test Comm I to say enter author I’ll say Steven Garcia license and I’ll say yes so now if we list that we see it has created our package.json file so let’s view this by expand here in mpm demo this is the package.json file that it created for us now let’s cover automating package.json creation if you prefer to skip the manual input and use default values for your package.json you can use the D- yes flag so previously we just did mpm and nit but instead you can do mpm andit D- yes so this command automatically fills in default values for all the fields in the package.json file speeding up the setup process so let’s cover the importance of the package.json file the first is Project metadata the package of Json file holds key information about your project which can be useful for package management and during deployment so let’s discuss dependency management it lists all the packages your project depends on allowing mpm to automatically install and manage these packages for you script shortcuts you can Define scripts and package.json that you can run with npm this is useful for tasks like starting the server running tests or custom build processes best practices one best practice is regular updates keep your package.json file updated as you add or remove dependencies update scripts or change project metadata Version Control include package.json in your version control system such as get Version Control to ensure that team members and deployment environments use the correct project settings and dependencies in conclusion the package.json file is a fundamental component of any nodejs project serving as the blueprint for managing the project settings and dependencies by starting your project with the creation of this file you ensure that all dependencies are correctly tracked and that your project metadata is well documented from the beginning this initial setup is crucial for maintaining a health manageable codebase as your project grows why is the package Json file crucial for managing dependencies and project metadata in a node.js project the package.json file is crucial in a node.js project because it serves as the central hub for managing project dependencies scripts and metadata it tracks all the libraries your project relies on ensuring consistent installation across different environments additionally it stores important project information such as the version author and Licensing details and provide scripts for common tasks making the project easier to manage share and deploy this file is essential for maintaining an organized and efficient code base how ises initializing a node.js project with mpm and knit contribute to better organization and maintainability of the Project’s codebase initializing a no JS project with mpm a nit contributes to better organization and maintainability by creating a package.json file that centralizes project metadata and dependency management this file keeps track of all libraries and modules the project depends on ensuring consistent setups across different environments it also allows you to Define scripts for common task making your workflow more efficient and the project easier to manage as it grows this structured approach prompts a well organized and maintainable code base from the start adding a third-party library to your node.js application integrating thirdparty libraries into your node.js project can enhance functionality without the need to write additional code libraries such as underscore provide a range of utilities for common programming task so Step One is choosing a library so begin by choosing using a library that suits your needs for instance underscore is a popular JavaScript library that offers helpful functional programming utilities you can search for underscore or other libraries on npmjs.com which also provides installation instructions and documentation for each package so step two is installing the library to add a library like underscore to your project use the mpm install command this command downloads the library from the mpm registry and adds it to your project so let’s open up the integrated terminal with command J we can run mpm install underscore alternatively you can use a shortcut mpm icore when you install a package using mpm two important things happen the first is an update to your package.json file so here when we install underscore it is added within the dependencies object this entry ensures that any one else working with your project repository can install the same dependencies and the second is Library storage the library files are downloaded and stored in the node modules directory within your project so here we see has created a node modules directory which contains our dependencies so step three is using the library in your application so after installation you can require and use the library in your application files so let’s create a new file in our mpm demo directory and name it index.js as that is the entry point of our application let’s close the sidebar now we can utilize the underscore Library so I’ll say require and underscore so by convention we use the underscore when using this library now we can say cons is even underscore and then the method sum so I’ll pass in an array 1 2 3 4 and five and for the second argument I’ll pass in a call back so a number if a number is divisible by two then we’ll log out let me make let me rename this to be is even then I’ll log out is even so this method sum checks if at least one of the elements is even let’s run this so I’ll say node index.js and here I see the output of true so in conclusion adding thirdparty libraries like underscore to your node.js projects streamlines development by allowing you to utilize pre-built functionalities this practice not only saves time but also enhances the capabilities of your application always ensure to use while maintained and trusted libraries manage your dependencies through package.json keep your projects organized and maintainable what are the key considerations When selecting and integrating third party libraries into a node.js project When selecting and integrating thirdparty libraries into a node.js project key considerations include ensuring the library is wellmaintained and widely used which indicates reliability and Community Support check for compatibility with your Project’s node.js version and evaluate the library’s documentation and features to ensure it meets your specific needs also consider the potential impact on your Project’s performance and security properly manage these dependencies in your package.json file to maintain an organized and maintainable codebase how does managing dependencies through mpm enhance the organization and maintainability of a node.js application managing dependencies through mpm enhances the organization and maintainability of a node.js application by automatically tracking all required libraries in the package.json file this ensures that all dependencies are documented and can be easily installed or updated by other developers or in different environments mpm also handles versioning preventing conflicts and ensuring consistent environments across different setups this structured approach helps keep the project organized and simplifies dependency management making the application easier to maintain over time using thirdparty libraries like underscore can significantly streamline complex operations and no JS applications so in our index.js file we imported our underscore Library so it’s common to use the underscore symbol as the variable name for this particular Library so the require function follows these steps to locate the under underscore module it first checks if underscore is a core node.js module failing that it looks for underscore as a relative or absolute path in the project lastly it searches within the node modules directory so the underscore Library provides a wide range of utility functions that are highly useful for working with collections arrays and objects for example to check if an array contains a specific item you can use the contains function so here I can comment this out so command and Port slash so I can say cons does contain uncore do contains so for the first argument I’ll pass an array containing one two and three and for the second argument I’ll pass the value two and let’s log out the result does contain so we’ll do up arrow and run and here we see the value true let’s say if I change this to be the value four then we would see that it does not contain the value of four to better understand all available functions and their uses in the underscore Library visit the documentation so when viewing this particular library on npmjs here when it says homepage you can view the documentation for the library that you installed so this can provide insights into additional methods and their potential applications in conclusion using libraries like underscore and nodejs projects helps to reduce the amount of code you need to to write while increasing functionality and readability it is essential for developers to familiarize themselves with importing modules and understanding the path resolution mechanisms of node.js to effectively manage and utilize various libraries this practice ensures your applications are both efficient and [Music] scalable what are the benefits of using thirdparty libraries like underscore and no. JS projects and how can they enhance the efficiency of your Cod cod using third party libraries like underscore and node.js projects provides ready-made utility functions that simplify complex task reducing the amount of code you need to write this enhances code efficiency readability and maintainability by leveraging well tested functions from libraries you can focus more on building unique features rather than Reinventing common functionalities leading to faster development and more robust applications how does understanding no. js’s module resolution process help and effectively managing and integrating external libraries into a project understanding no. js’s module resolution process helps in effectively managing and integrating external libraries ensuring that you know how node.js locates and loads modules this knowledge allows you to correctly structure your project avoid conflicts and troubleshoot issues related to module pass it also ensures that the right version of dependencies are used which is crucial for maintaining a stable and predictable development environment this leads to smoother integration of external libraries and more reliable application [Music] Behavior When developing applications with no JS managing external libraries and dependencies is commonly handled using mpm which stands for node package manager so here’s how you can install a package like axios which is widely used for making HTTP requests to apis so we’ll open up our integrated terminal let’s clear this out we’ll use mpm and then I for install and then the name of the package which is axios so this command fetches the package from the mpm registry and installs it into your project you can view our package.json file and here we see axos is now included in the dependencies object if we view our no modules we also see the axios has been installed here so you’ll notice that it contains not only axios but also several other directories these are dependencies that axios requires to function properly so we can close this directory and navigate back to our index.js file so let’s discuss dependency management so when considering the file structure in the past mpm used a nested structure where each package would have its own known modules directory containing its dependencies this often led to duplication and a deeply nested directory structure which would cause path L issues especially on windows so for the current approach now mpm installs all dependencies in a flat structure in the root node modules directory of your project this change helps avoid redundancy and the complications of deeply nested dependencies handling version conflicts if different packages require different versions of the same dependency mpm will Nest the conflicting version locally within the requiring packages directory to avoid version clashes at the root level so let’s discuss the benefits of the current approach the first being simplification the flat structure simplifies dependency management by reducing redundancy and the potential for version conflicts across your project the second benefit is efficiency it minimizes dis space usage and improves installation speed since mpm no longer needs to install multiple instances of the same package across different locations the third benefit is compatibility it reduces issues related to file pad limits on certain operating systems which is particularly beneficial for Windows users so let’s go over a practical example with the axos library so now that we installed it we can start using it in our nodejs application to make HTTP requests so here’s a simple example to include axios in our project so we can do const axios use our require function the name of it is axios let we close the sidebar so we can do a.get for making a HTTP get request and we’ll make a request to an open source URL so https Json placeholder do typec code.com SL too SL1 then we’ll do then cuz it returns a promise which we will cover in the next section so response then we want to log this out response.data we’ll also include or chain catch for handling if any err occurs so we will log out the air console. a air. message and we’ll end that with the semicolon also we need to add another parentheses here to get rid of those errors so let’s run this with node index.js and here we see the data that we retrieved from this backend endpoint so this object contains a user ID an ID a title and a property of whether it is completed or not for this to-do item so in conclusion installing and managing node packages with mpm is a straightforward process that enhances the functionality of your applications understanding how mpm handles dependencies allows you to better organize and optimize your projects by using tools like axios developers can easily make HTTP requests in their applications making the development process more [Music] efficient what are the advantages of mpm’s flat dependency structure in modern node.js projects particularly in terms of efficiency and compatibility mpm’s flat dependency structure improves efficiency by reducing redundancy as it avoids multiple copies of the same package being installed in different locations this structure also minimizes disc space usage and speeds up installation times in terms of compatibility it reduces the likelihood of Path Lane issues especially on Windows and simplifies dependency management by making the directory structure less complex and easier to navigate this approach leads to a more streamlined and manageable project setup how does understanding mpm’s dependency management process benefit developers when integrating external packages like axios into a node.js application understanding mpm’s dependency management process benefits developers by ensuring that they can effectively handle and resolve potential conflicts between different versions of packages required by their node.js application it helps maintain a clean and organized project structure preventing issues like redundant installations or version mismatches this knowledge is crucial when integrating external packages like axios as it ensures smooth installation compatibility and Optimal Performance of the application leading to a more reliable and maintainable code [Music] base so first let’s discuss the role of know mod modules so its role is the storage of dependencies so let’s go over managing node modules and nodejs projects when working with node.js the node modules directory can become quite large because it contains all the packages you’ve installed using mpm along with their dependencies here’s how to efficiently handle this directory especially in collaborative environments so node modules hold all the packages that your application needs to run which are installed based on the list of dependencies found in your package.json file so why exclude known modules from Version Control so when working with applications we use G Version Control in order to manage our project as well as collaborate with other developers now we want to exclude the no modules directory when working with virion control the first reason being is size considerations this folder can become quite large and grow to hundreds of megabytes or more due to the nested dependencies typical in node.js projects including it in vers control would significantly increase the size of your repository and slow down operations like cloning and pulling changes the second reason is reproducibility so every dependency and its exact version is already specified in our package.json file so here if I view that so this means that node modules can be recreated on any Machine by running mpm install so there’s no need to include it in Version Control so let’s discuss these steps to exclude node modules so we want to exclude the known modules when using get Version Control and this is essential for keeping our repository clean and lightweight so I open up the integrated terminal with command J so in this course I won’t cover get Version Control in depth I’ll just provide a quick explanation of how you can exclude no modules so we can initialize get in our current project so I’ll say get a nit so this initializes a new get repository so we can now use Version Control to manage our project we can do get status and we can all the files in our project now we want to create a dog ignore file so this file tells G which files or directories to ignore in your projects so I’ll create that here I’ll say touch. get ignore so let me close this with command J and we’ll view this file we just created so this is a hidden file and that’s why I prefix it with a period so we want to add the following line and this will specify that the node modules directory should not be tracked by git so I’ll say say node modules and then slash indicating the directory so we save this so now when we run get status to see what files are in our project here it doesn’t include the node modules directory so we can now add and commit our changes so we will add our changes to the staging area so we’ll say get ad and then period meaning all files let’s do get status again and here we see our project files are now staged and ready to be committed so we can do get commit Das message and I’ll name it initial commit so now these files are being tracked and I can collaborate with other developers who also have access to this project and are using get Version Control so let’s discuss restoring no modules if you clone the project or need to restore dependencies simply run mpm install in your command line so this command looks at your package.json file and installs all the necessary packages from the mpm registry so in conclusion excluding known modules from Version Control is a best practice in nodejs development it keeps your project repository manageable speeds up operations like cloning and ensures that all developers are working with the same dependencies as defined in package.json so this approach Fosters a clean more efficient development environment [Music] why is it important to exclude the node modules directory from Version Control and how does it benefit the management of a node.js project it is important to exclude the node modules directory from Version Control because it significantly reduces the size of the repository making operations like cloning and pulling changes faster the node modules can can be recreated at any time by running mpm install which installs all necessary dependencies based on the package.json file this approach ensures that everyone on the project works with these same dependencies while keeping the repository clean and efficient to manage what are the best practices for managing dependencies and restoring them in a node.js project particularly in a collaborative environment best practices for managing dependencies in a node.js project include using a package.json file to track all dependencies and their versions this ensures consistency across different environments in collaborative environments it’s crucial to exclude the known modules directory from Virg control to keep the repository lightweight and avoid unnecessary duplication to restore dependencies use the mpm install command which installs everything listed in package.json ensuring all team members work with the same setup reducing the risk of conflicts or errors so let’s cover understanding semantic versioning and nodejs semantic versioning is a standard for versioning software which is widely adopted in the development Community including nodejs packages it helps developers understand the potential impact of updating a package so let’s discuss the components of semantic versioning a typical version number format includes three components the first being the major version the minor version and a patch version so for the major version this indicates significant changes that make API changes which are not backwards compatible upgrading to a different major version could break existing functionalities so for the minor version this adds new features in a backwards compatible manner it does not break or change existing functionality but adds to it and for the patch number this includes bug fixes and minor changes that do not affect the software’s function ality or API so it’s also backwards compatible so for example for the axios package that we installed one is the major version seven is the minor version and five is the patch version let’s discuss the carrot and the Tilda inversion name so here we see the semantic version number is prefix with a carrot so when you see a carrot in front of a version number in package.json it means mpm can install updates that do not modify the leftmost nonzero digit in the semantic versioning string so here for this particular example so here when considering axios since it is prefixed with a carrot it can install any version as long as the major version does not update even if the minor or patch version is higher than specified in our package.json file now you may also see a Tilda symbol so a Tilda allows updates that only change the most right-and digit that is not zero in the semantic versioning string assuming that the most right hand digit is the patch version so for example if the version was 1.3.6 mpm can update to 1.3x where X is any patch number greater than six this means you get bug fixes and minor changes that are unlikely to break your project so we can discuss installing packages with mpm so when someone CLS a repository and runs mpm install mpm installs the dependencies based on the rule set in the package.json file using the Carro symbol or tiled operator this allows for a controlled upgrade path that balances stability with getting timely patches and features specifying exact versions in some cases especially when ensuring absolute consistency across environments or dealing with very sensitive dependencies you might want to pin dependencies to an exact version to do this you can specify the version without any prefix this configuration guarantees that no version larger than the semantic version number specified will be installed avoiding any issues due to minor updates or patches in conclusion understanding how semantic versioning works with mpm helps manage dependencies more effectively ensuring that applications remain stable while still receiving necessary updates and Bug fixes it allows developers to control the risk associated with automatically updating packages and ensures that all team members and production environments run the same versions of each package how does semantic versioning help developers manage dependencies and ensure stability and node.js projects semantic versioning helps developers manage dependencies by clearly indicating the impact of updates through version numbers it uses three components a major minor and Patch to Signal the type of changes made major versions indicate breaking changes minor versions add new features without breaking existing functionality and Patch versions include Backward Compatible bug fixes this system ensures that developers can update packages safely maintaining stability while still receiving important updates and fixes reducing the risk of unexpected issues in your project what are the implications of using the carrot symbol or toota operator inversing when managing package updates and no. Js using the carrot inversing allows updates to minor and Patch versions while keeping the major version stable ensuring backwards compatibility the Tilda operator restricts updates to only patch versions keeping both major and minor versions fix these operators help manage package updates by allowing controlled upgrades the carot symbol offers more flexibility by permitting minor updates while the Tilda operator provides stricter control reducing the risk of breaking changes this helps maintain stability while still applying necessary updates so let’s discuss checking installed versions of a nodejs package so when managing a nodejs project it’s essential to keep track of the versions of packages installed to ensure compatibility and stability so here’s how you can determine the versions of the packages you have installed so viewing installed versions the first thing you can do is manual checking sometimes you may want to manually check the version of a specific package installed in your project this could be done by looking at the package.json file within each package’s directory and know modules so if I were to expand know modules and View axios and then package.json I see that the exact version installed is 1.7.5 so if I close this now we get back to our package at Json so the second way that you can check your installed version is using mpm commands so this is a more efficient way to view all installed packages and their versions by using the mpm list command so this displays the tree of packages installed in your project running this command in your project directory will show you a tree structure of all packages including their dependent packages so let’s open up the integrated terminal and we’ll run mpm list so this is a small project so we see our two mpm packages that we have in installed however this output can be extensive because it includes all nested dependencies in the case when we’re considering a large production application so the third way that we can check the version that we have installed is by running mpm list and then depth set to zero so if you’re only interested in the top level packages so those directly specified in your projects package at Json you can simplify the output using the depth set to zero option so this command restricts the output to the first level of the dependency tree showing only the packages that you have directly installed in your project so why this matters the first reason why this matters is compatibility knowing the exact versions of the packages you have installed helps manage compatibility between different parts of your application and its dependencies the second reason is debugging when troubleshooting issues in your application knowing the exact versions can help determine if a specific version of a package might be causing the problem the third reason is updates and upgrades regularly checking installed package versions can help you decide when to upgrade to a newer version and take advantage of new features or important bug fixes in conclusion effectively managing package versions in a node.js project is crucial for maintaining the stability and reliability of your applications using tools like mpm list helps streamline this process are providing a clear overview of what is installed thus enabling better version control and dependency management by routinely checking and upgrading your dependencies you can ensure your application remains secure efficient and up to [Music] date why is it important to regularly check the versions of installed node.js packages in a project regularly checking the versions of installed node.js packages is important to ensure compatibility and stability in your project it helps you identify potential issues caused by outdated or conflicting dependencies and allows you to take advantage of security patches bug fixes and new features keeping track of package versions also AIDS in debugging as knowing the exact versions can help pinpoint problems related to specific updates or changes in the package ecosystem this practice contributes to maintaining a reliable and secure application how can using npm commands help streamline the process of managing and verifying package versions in a node.js project using mpm commands streamlines managing and verifying package versions by providing quick and detailed insights into the installed dependencies commands like mpm list display all installed packages and their versions while options like the depth set to zero focus on top level dependencies making it easier to track and manage them this approach helps ensure your project remains stable and up toate by allowing you to easily monitor an update packages as needed all from the command line when working with mpm packages it is often necessary to understand their dependencies versions and other metadata to ensure they fit well within your project so let’s go over viewing package metadata on npmjs.com so here on the mpm official website search for a package you’re interested in such as axios so in this input field I’ll look up axios we will click on the official package so on the package page you will see comprehensive details including the latest version the licensing the GitHub repository the number of weekly downloads and the package dependencies so using mpm commands to view package information for a more direct and detailed exploration of a package metadata you can use mpm commands so open up the integrated terminal with command and J move this up so to see a summary of metadata for a package directly in your command line you can use the mpm view command so I’ll do mpm View and then the name of the package so this case it’s axios so this command let’s move this up so this command outputs information such as the latest version the description of the package the main entry point the repository keywords the author the license now let’s go over viewing dependencies if you’re specifically interested in what dependencies a package has you can directly view that information by typing in mpm view the name of the package so axios and then dependencies so this will list dependencies required by axios showing you what packages it relies on to function so checking available versions to view all versions of a package that have been published to mpm you can use mpm view the name of the package and then versions so this is particularly useful if you need to upgrade or downgrade to a specific version it lists every version available helping you make informed decisions based on the features or fixes included in each so a practical usage of package information the the first practical usage is for making upgrades knowing the version and dependencies can help you decide whether to upgrade a package you can assess the changes between versions and determine if the upgrade addresses any issues you face or offers new features you need compatibility checks viewing dependencies ensures that the package is compatible with other components of your application especially if there are specific versions of dependencies that your application requires debugging and issue resolution detailed metadata can assist in debugging issues related to package configurations or interactions between multiple packages in conclusion understanding how to retrieve and utilize metadata about mpm packages is essential for Effective package Management in no. JS projects whether it’s through browsing npmjs.com for a high level overview or diving deep with mpm view commands for specific details these tools provide critical insights that help maintain the health and functionality of your application [Music] why is it important to regularly check the dependencies and versions of mpm packages in a nodejs project and how can this practice impact the stability and compatibility of the application regularly checking the dependencies and versions of mpm packages in a node.js project is crucial for maintaining stability and compatibility it ensures that all packages work well together preventing conflict that could arise from incompatible versions this practice also helps identify when updates or security patches are needed reducing the risk of bugs or vulnerabilities by staying on top of package versions developers can keep the application reliable and ensure it runs smoothly across different [Music] environments When developing applications you might occasionally need to install a version of a package that isn’t the latest due to compatibility issues specific features or other dependen in your project this can be accomplished easily using mpm commands specifying package versions to install a specific version of a package append the version number to the package name using the at symbol for example to install a version 1.7.3 of axios you would do mpm install axios then the at symbol 1.7.3 so this command tells mpm to fetch and install the exact version of axios from the mpm register so verifying installation after installing the package it’s a good practice to verify that the correct versions have been installed you can use the mpm list and then the flag D- depth set to zero command to check the versions of the top level packages installed in your project so we can do npm list D- depth and set that to zero so this command provides a list of all packages directly installed in your project ignoring their dependencies and specifies their version numbers it allows you to quickly verify that the correct versions are installed so why specify versions the first reason is compatibility certain projects or dependencies might require specific versions to maintain compatibility breaking changes in new versions could disrupt the functionality of your application the second reason is bug fixes some versions might include bug fixes not present in newer versions or new versions might introduce bugs that were not present in previous versions and the third reason is for features older versions might have features that have been deprecated in the latest release but are still necessary for your project in conclusion understanding how to specify and install particular versions of packages with mpm is crucial for precise dependency management and software development this practice helps ensure that your application remains stable and behaves as expected regardless of changes and updates in the package ecosystem by specifying package versions you maintain control over your development en and reduce the risk of unexpected issues why might a developer need to install a specific version of an mpm package how does this practice contribute to project stability a developer might need to install a specific version of an mpm package to ensure compatibility of other dependencies maintain access to certain features or avoid bugs introduce and newer versions by specifying and controlling the exact version the developer can stabilize the project ensuring the updates or changes in the package ecosystem don’t unexpectedly break the application or alter Its Behavior this practice helps maintain a consistent and reliable development environment across different setups what are the benefits of verifying installed mpm package versions after installation and how does it ensure consistency in a nodejs project verifying installed mpm package versions after installation ensures that the correct versions are in place which is crucial for maintaining consistency across different development environments this practice helps prevent unexpected issues caused by version mismatches ensures compatibility with other dependencies and supports stable project Behavior by confirming that the specified versions are installed you can confidently manage dependencies and avoid problems that might arise from automatic updates or version conflicts [Music] so let’s go over managing outdated mpm packages maintaining the dependencies of your application ensures you benefit from the latest bug fixes performance improvements and security patches here’s how to identify and update outdated packages in your nodejs project I’ll open
up the integrated terminal so command J and I’m currently in the mpm demo directory that we created so this contains our package.json file to check which packages are outdated in your project you can use the mpm outdated command this will display all dependencies with newer versions available showing the current version you’re using the latest version available and the desired version the desired version is the highest version permitted by your versioning rules in your package.json file so currently for our project here if I view the dependencies we have installed we have axios and we have underscore both of these are currently the latest versions so I run mpm outdated nothing will show up since these are the latest possible versions to demonstrate that I’ll do mpm outdated so currently there is no result because I have the latest versions navigate outside of this directory and so if I run mpm outdated this will show the outdated packages that I have installed globally on my system so here this demonstrates the current version I have installed the desired version and the latest version so let’s go over updating packages to update old packages to the newest versions that do not include breaking changes so this typically includes minor updates and patches you can run the following command saw Run mpm update so this command updates the packages within the semantic version and constraints specified in your package.json file it will not update packages to a new major version that could contain breaking changes so let’s go over handling major updates sometimes you may need or want to update packages to their latest major versions which might include breaking changes to handle this you can use a tool called mpm check updates so let’s install that globally so I’ll use the sudu command mpm install dasg then mpm check updates I’ll enter my password so now we can run mpm check updates to see which packages have new major versions available so I can run mpm check updates you can then use the tool to update your package.json to the latest major versions so you would do mpm check updates and then the flag – or the shortcut ncu dasu so to reinstall dependencies after updating package. Json with mpm check updates the packages themselves are not automatically updated in your node modules directory you need to reinstall them to sync your directory with the updated package at Json so you can run mpm install let’s go over best practices the first best practice is testing always thoroughly test your application after updating dependencies especially when major versions are involved to ensure no breaking changes disrupt your application the second best practice is Version Control commit changes to your package.json and package lock Json file after Updates this ensures that your team or deployment environments use the same versions so in conclusion regularly updating the mpm packages in your node.js projects is crucial for maintaining the security efficiency and reliability of your applications tools like mpm check updates helps manage the life cycle of your dependencies allowing you to take advantage of the latest improvements while car carefully managing the risk of breaking [Music] changes what are the best practices for safely updating mpm packages particularly when handling major version changes best practices for safely updating mpm packages include first to review updates so use tools like mpm outdated or mpm check updates to identify and review available updates the second is to test thoroughly after updating especially when upgrading to a major version thoroughly test your application to catch any breaking changes third is to use Version Control always commit changes to package.json and package lock. Json to ensure consistency across environments and fourth update incrementally where possible update packages incrementally rather than all at once to isolate issues more easily these steps help maintain stability and minimize the risk of [Music] disruptions managing dependencies and node.js projects in node.js development it’s important to differentiate between dependencies required for the application to function and production and those needed only during the development process so let’s go over understanding dependencies first let’s consider production dependencies these are the packages your application needs to function correctly in the production environment such as Frameworks like Express or a database Library like or any other libraries necessary for the runtime execution of your app so the second type of dependency is development dependencies development dependencies are tools and libraries used only during the development process such as compilers like Babel testing Frameworks like mocha or static analysis tools like JS these are not needed in production and should not be bundled with your production build so let’s go over installing development dependencies to install a package as a development dependency use the save Dev flag this tells mpm to save the package under Dev dependencies in your package.json file this distinction is crucial for keeping production environments Lightweight by excluding unnecessary packages so we going to run the command mpm install JS hint save D so here running it in the directory that contains the package.json file and I see another property has been added named Dev dependencies which includes the package that I just specified so let’s go over the benefits of correctly categorizing dependencies the first is optimize production builds by segregating development dependencies you can ensure that your production environment only installs what is necessary reducing deployment size and potentially improving application performance the second benefit is clear project organization keeping a clear distinction between dependencies and Dev dependencies in your package.json file helps maintain organization and Clarity this makes it easier for other developers to understand the project setup managing node modules both production and development packages are stored in the node modules directory when installed the distinction in package at Json helps mpm understand which packages to install in different environments and you would use the environment variable node M and set it to development or to production so let’s discuss deploying to production when deploying your application you can ensure that only production dependencies are installed by setting the environment variable not environment to production and running mpm install mpm will skip developer dependencies in this case so in conclusion properly managing production and development dependencies is vital for efficient development workflows and optimized production deployments by categorizing your packages appropriately and package at Json you can maintain a lean an efficient application setup that ensures only necessary packages are included in production environments this practice not only optimizes performance but also enhances security by minimizing the attack surface of your [Music] application why is it important to differentiate between production and development dependencies in a nodejs project differentiating between production and development dependencies in a no. JS project is crucial because it ensures that only the essential packages needed for the application to run are included in the production environment this reduces the deployment size improves performance and minimizes security Risk by excluding unnecessary tools used only during development such as testing Frameworks or build tools proper categorization also helps maintain a clean organized project structure making it easier to manage and understand how does proper management of dependencies impact the efficiency and security of a node.js application and production proper management of dependencies in a node.js application impacts efficiency by ensuring that only necessary packages are included in the production environment reducing the application size and improving performance it also enhances security by minim minimizing the attack surface as fewer packages mean fewer potential vulnerabilities by installing only production dependencies you avoid including unnecessary tools that could introduce risk leading to a leaner more secure and optimized application and production so let’s go over uninstalling a package over time you may find that certain mpm packages are no longer needed in your application removing these packages helps keep your project lean and prevents unnecessary bloat in your no modules directory to remove an installed package you can use the mpm uninstall command followed by the package name this command removes the package from your node modules directory and updates the dependency list in your package.json file so if I wanted to remove the JS hint package that we installed in the previous lesson I can do mpm uninstall and then the name of the package so in this case JS I could also use the Shand which is mpm and then un then the name of the package so here I see my package.json file has been updated so let’s discuss the effects of uninstalling when you uninstall a package mpm automatically updates your package.json file removing the package from the list of dependencies or Dev dependencies depending on where it was listed so updating known modules the corresponding package directory and its contents are removed from the node modules folder this cleanup helps reduce the overall project size and and declutters your development environment so let’s discuss best practices the first is to verify dependencies before uninstalling a package make sure it is not required by any other part of your application you can check where and how a package is used in your project to avoid removing a package that is still in use the second best practice is to commit changes after uninstalling a package and verifying that your application still functions as expected commit the changes to your version control system this keeps your repository up toate and allows other developers to be aware of the changes and dependencies the third best practice is regular maintenance periodically check your package at Json file and your project dependencies to identify and remove packages that are no longer necessary this practice keeps your project clean and minimizes potential security risks associated with outdated or unused packages in conclusion regularly updating and cleaning up your Project’s dependencies are crucial steps in maintaining a healthy code base uninstalling unused pack P ages reduces the complexity of your project decreases lad times and lessens the risk of conflicts or security vulnerabilities by keeping your package at Json and node modules directory streamlined you ensure that your project remains efficient and [Music] manageable why is it important to regularly remove unused mpm packages from a node.js project how does this practice contribute to project maintenance regularly removing unused mpm packages from a nodejs project is important because it helps keep the project lean and efficient it reduces the size of the node modules directory improving load times and minimizing potential security risk from outdated or unnecessary packages this practice also simplifies project maintenance by reducing clutter preventing dependency conflicts and ensuring that only essential packages are included in the application keeping the coase clean and manageable enhances the overall health and stability of the project what steps should developers take before and after uninstalling mpm packages to ensure that node.js project remains functional and up toate before uninstalling mpm packages developers should verify that the package is not in use by checking where and how it is utilized in the project after uninstalling they should thoroughly test the application to ensure functions correctly without the remove package it’s also important to update the version control system by updating the changes to package. Json and package lock. Json this process ensures that the project remains functional clean and up to date so let’s go over working with global packages in node.js development some packages are not tied to a specific project but are rather tools or utilities used across multiple projects these are typically in install globally on your system so let’s go over installing Global packages first let’s discuss the purpose of global installation Global packages are typically command line tools or utilities that you want to run from anywhere on your system not just within a specific project for instance this could include package managers like mpm itself or project scaffolding tools like angler CLI which is a framework for building web applications these two packages for example are commonly installed globally to install a package globally you would use the – G or hyphen G or the– Global flag with the mpm install command this tells mpm to place the package in a special systemwide location that no JS can access from any directory so for example if you installing the angler web framework you would run the command mpm install then the flag DG and then the name of the package which is angler SL CLI this installs the angler CLI globally which you can then use to create new projects from anywhere on your system so step three is updating mpm itself mpm can also be updated globally using the same flag this is useful to ensure that you have the latest features and security updates so to do this you would run the command sudu mpm install DG mpm now a note for permissions on Mac OS and Linux you might need to use the Pudu command to install Global packages this depends on your system’s permission settings however setting up mpm to run without Pudu can avoid permission issues and is recommended for security reasons managing Global packages to manage and update your Global packages you can check which ones are outdated by running mpm outdated and then the flag – G this command lists all globally installed packages that have newer versions available upgrading Global packages if you find outdated Global packages you can update them by reinstalling with the mpm install –g command specifying the package you wish to update let’s discuss best practice IES for Global packages the first is to minimize Global installations install packages globally only when necessary overuse of global installations can lead to version conflicts between projects and complicate dependency management the second best practice is regular updates keep your Global packages updated to leverage new features and security enhancements the third best practice is to document globally installed tools for team projects document the tools required globally so all developers set up their envirment consistently in conclusion Global mpm packages are essential tools for development offering functionalities that extend across multiple projects properly managing these packages ensures that your development environment is both effective and secure by regularly updating and maintaining the global packages you can avoid potential conflicts and keep your system optimized for all your development [Music] needs what are the benefits and potential risks of installing mpm packages globally instead of locally in a node.js development environment so the benefits of global installation is that Global mpm packages are accessible from any directory on your system making them ideal for command line tools or utilities used across multiple projects such as project scaffolding tools or linters so for the potential risk overusing Global installations can lead to version conflicts between projects as different projects may require different versions of the same tool it can also complicate dependency management and make it harder to maintain consistent environments across different machines or for different team members how can developers effectively manage and maintain Global mpm packages to ensure a consistent and secure development environment developers can effectively manage and maintain Global mpm packages by following these steps the first is to minimize Global installation so only install packages globally when necessary to avoid version conflicts and simplified dependency management step two is regular updates frequently check for outdated Global packages using the mpm outdated and- G flag and update them to ensure security and access to the latest features and step three is documenting requirements clearly document any Global tools needed for a project ensuring that all team members can set up consistent and compatible environments these practices help maintain a stable and secure development environment so let’s go over publishing a package creating and Publishing your own mpm package can be a rewarding process allowing you to share your work with the wider no. JS community so to do this step one is to set up your package so let’s open up the integrated terminal and I will make a new directory and I’ll just call this new library we’ll change into this new directory so step two is to initialize the package we’ll use mpm and nit to create a package.json file with the default values so we will pass the D- yes flag which Auto accepts the default options so we can run mpm and nit D- yes so let’s create the package of Json file so we see our new directory here opening up the integrated terminal again with command J let’s scroll down so step three is to create the main file so we’ll create an index.js file where we will write the code for our package so from the command line I can do touch index.js to create that new file so we see that added here now we will add some functionality so I can say module. exports. add and I’ll assign this to a function which takes two parameters and Returns the result of adding them so a plus b and this with a semicon so now you need to create or use an mpm account so for the account setup if you don’t already have an mpm account you will need to create one this could be done from the mpm website or directly from the command line so you can run mpm add user if you already have an account and simply log in with mpm login and you will be prompted to enter your username password and email address so step three is to publish your package so to prepare for publishing ensure that your package.json file includes a unique name for your package mpm requires that package names be unique to the registry so now you’re ready to publish the package once you are ready and have verified that all information is correct you can publish your package to mpm using the command mpm publish so this command uploads your package to the mpm registry making it available for others to install so now you want to verify installation you want to test it so to ensure that your package can be installed from another project create a new directory Elsewhere on your system and install it so so for example you can do make directory and then name that directory and change into it then you can run mpm install and then that package that you created so test the functionality in this new project environment to confirm everything works as expected so after publishing you want to be sure to perform updates and maintenance so after publishing you might need to update your package with improvements or bug fixes so make changes in your local project increment the version number in your package.json file following the semantic versioning rules and run mpm publish again so now discuss metadata and visibility mpm automatically adds metadata to your publish package this includes information like the publication day version history and dependencies this metadata is crucial for users of your package to understand its history and stability in conclusion publishing a package on mpm is a straightforward process but requires careful setup and attention to detail to ensure that the package is functional and useful to others by following the steps you can contribute your own modules to the npm ecosystem and potentially help thousands of developers [Music] worldwide what are the key steps involve in creating publishing and maintaining an mpm package for the node.js community the key steps to create publish and maintain an npm package involve first setting up so create a directory initialize it with npm and nit and write your packages code step two is publishing so create or log an mpm account ensure your package name is unique and publish it using mpm publish step three is verifying so test the package by installing it in a different project to ensure it works as expected and step four is maintaining update your package as needed increment the version number and republish it to keep it current and useful for others why is it important to verify and test your mpm package after publishing and how can this impact its usability by other developers verifying and testing your mpm package after publishing is crucial to ensure it works as intended in different environments this step helps identify and fix any issues that might arise ensuring that the package is reliable and userfriendly for other developers if a package is not properly tested it can lead to errors and frustrations for users reducing its adoption and usability thorough testing enhances the package’s credibility and usefulness within the developer community so let’s go over updating a published package when you made changes to your mpm package such as adding new features or fixing bugs you must update the package’s version before republishing it this ensures that users can keep track of changes and upgrade their installations appropriately so step one is to make changes to your package so here we can modify the code so in your package directory you can make any necessary changes so for example if you wanted to add a multiplication function to your package so I can say module. exports do multiply set that to a function which takes two parameters and returns a * B so step two is to update the package version in your package.json file so here the current version is 1.0.0 and before we can publish it we need to update its version so mpm uses semantic versioning which includes major minor and Patch updates so once again the major version makes incompatible API changes the minor version adds functionality in a backwards compatible Manner and the patch version makes backwards compatible bug fixes so from the command line we can run mpm version major for breaking changes mpm version minor for new features that are backwards compatible mpm version patch for backwards compatible bug fixes so this case we can run mpm version and then minor and here we see our version has been updated in our package or Json file to be 1.1.0 this command updates the version number in your package Json and creates a new commit if your package directory is a g repository so step three is to publish the updated package so after updating the version you are now ready to publish the updated package P AG so you can run mpm publish if you try to publish without updating the version mpm will return an error because the package version must be unique following the version update the publish command should succeed additional considerations before publishing an update thoroughly test your package to ensure that new changes do not introduce bugs or break existing functionality documentation update your readme markdown file for any documentation to reflect changes made in the new version especially if You’ added new features or May significant modifications in conclusion updating a published mpm package requires careful attention to version management and compatibility by following semantic versioning rules you can communicate the nature of changes in your package updates to users effectively always ensure that your updates are well tested and documented which helps maintain and enhance the package’s utility and credibility in the community why is semantic versioning important when updating npm package how does it help communicate changes to users semantic versioning is important when updating an mpm package because it clearly communicates the type of changes made helping users understand the impact on their projects by using version numbers to indicate major breaking changes minor new features or patch bug fixes developers can manage expectations and allow users to update dependencies safely this practice ensures that users can confidently upgrade to newer versions without unexpectedly breaking their applications which best practices should developers follow when updating and republishing an mpm package to ensure its reliability and usability when updating and republishing an mpm package developers should follow these best practices the first is to use semantic versioning clearly communicate the type of changes which could be major minor or patch to users then do thorough testing ensure all new changes are well tested to prevent introducing bugs or breaking existing functionality third update documentation provid read me markdown files and other documentation to reflect the latest changes and new features then commit those changes and tag if necessary if using Version Control commit the changes and tag the new version before publishing these practices help maintain the package’s reliability and usability [Music] synchronous versus asynchronous code so let’s set up a new project we’ll open up the integrated terminal with command J or control J if you’re on Windows we’ll run the command make directory and we’ll name it async demo let’s change directory into that new folder we created now we want to initialize a new node.js project we do that with mpm anit then we’ll pass in the flag D- yes to accept the defaults just created our package.json file we clear this out now we want to create a new file we could do this from the command line and we will run touch index.js so now if we expand this directory and click into our index.js file first we will write synchronous code so we can add the following console statements we can do log and then tab for that keyboard shortcut and we’ll log out the string before so now we’ll do shift option and down arrow to copy this line and then we’ll do after so this code is a simple example of synchronous or blocking programming so here the program awaits for the first console log statement to execute and to complete before moving on to the second one we can just output this node index.js and we get our expected console log output so introducing asynchronous programming in contrast asynchronous programming allows the program to move on to other tasks before the previous ones have completed so we will modify our file here we will use the set timeout method set timeout so for the parameter we will pass in a callback function so we’re using the modern es6 syntax or eror functions So within this code block we can I’ll say a comment simulate a call to the database so let’s say we’re making a call to a database that contains information on our grocery list you can do log and we’ll say reading a grocery item from a database so for set timeout the first argument that we pass in is the call back function it also accepts a second argument which is the time to wait before executing this code this is represented in milliseconds so we’ll say 2000 represent 2 seconds and let’s execute this program so let’s open up the integrated terminal with command J up arrow and run it again so here we see before then after for our set timeout it waits 2 seconds and then it logs out this console log statement so this is an example of asynchronous programming so this demonstrates that set timeout schedules the task to be performed later without blocking the execution of subsequent code understand asynchronous programming asynchronous programming is not the same as concurrent or multi-threaded programming in OJs asynchronous code runs on a single thread it’s crucial because operations involving disk or network access in node.js are handled asynchronously allowing the program to remain responsive asynchronous programming helps ensure that your application can handle multiple operations efficiently without getting stuck waiting for one task to complete before starting another [Music] how does asynchronous programming improve the efficiency and responsiveness of a node.js application especially in handing iio operations asynchronous programming improves the efficiency and responsiveness of a node.js application by allowing the programs to continue executing other tasks while waiting for I operations such as a database call or file access to complete this non-blocking approach ensures that the application remains responsive and can handle multiple operations simultaneously rather than being helded up by slow operations as a result the application can serve more users and manage more task without delays or bottlenecks leading to better performance overall what are the key differences between synchronous and asynchronous programming in the context of node.js and why is it important for developers to understand these differences synchronous programming and node.js executes task one after the other blocking the execution of subsequent code until the current task is finished asynchronous programming on the other hand allows the program to initiate tasks like iio operations and move on to other tasks without waiting for the previous ones to complete understanding these differences is crucial because asynchronous programming helps prevent Bott necks making applications more efficient and respons by not allowing a single slow operation to Hal the entire [Music] program so let’s discuss patterns for dealing with asynchronous code let’s first go over an example of incorrect synchronous code so we’ll buildt upon the previous code snippet that we did in our previous lesson so we have our console log statement outputting before and then we call set timeout so let’s abstract this and let’s put this into a function so we use the function declaration syntax and we’ll name it get grocery item and it takes in an ID or curly braces and let’s move this so we’ll copy this and we can paste it in the block so rather than just console logging we will return a JavaScript object which contains an ID and a name so we’ll say apples is the name of the grocery item and it with a semicolon so now let’s call this function I can say cons grocery item say get grocery item and I’ll pass in the value of one is the ID let me just add a comment here so we know what to expect so we cannot get a grocery item like this as we will see then let’s do console log we will output the grocery item so note that when we do this this will have the value of undefined the reason is because when we call get grocery item the item isn’t returned immediately because we call set timeout there’s a 2C delay before we get this grocery item object let’s open up the integrated terminal up arrow and we will execute this file so here we get before undefine then we get this output after and then this console log statement within the set timeout so this function get grocery item is intended to simulate fetching an item from a database however due to the set timeout function it does not return the grocery item immediately instead it schedules the operation to occur after 2 seconds so the console log and then the grocery item executes before the grocery item data is available resulting in undefined the key reason this does not work as intended is because set timeout is asynchronous the function does not wait for 2 seconds to return the grocery item data rather it returns immediately and the code continues executing so let’s correct this approach when dealing with asynchronous operations like database calls the result is not immediately available here are three common patterns to handle a synchronous code in JavaScript the first being callbacks the second being promises and the third being a syn8 so first let’s discuss using callbacks so we will fix our code to utilize that pattern so we have our console lock statement actually let’s comment this out and we will start again from scratch so here can do console.log I’ll put the string before then we can Implement get grocery item this takes in an ID and it will accept a second parameter which is a callback function we can call set timeout and this also accepts callback function with a 2C DeLay So within it let it’s output I’ll say reading a grocery item from a database and we’ll say call back then we’ll pass in the object right the grocery item object the ID and then the name which we will say is Apple and that with the semicolon so we want to utilize the get grocery item function in its implementation it is using the asynchronous method of set timeout so we can call get grocery item pass in one as the ID and then for the call back we specify an es6 arrow function right so we’re using the modern syntax grocery item arrow and then the curly braces and here we will Define our implementation and here we will just output the GR item that is returned right so this object is passed into the call back and so this object will be the grocery item that we are outputting to the console and then one more log which is the string after so now we will execute this up Arrow so we can run this so we get before and after then it waits 2 seconds and then we see reading a grocery item from a database and then our expected grocery item object if I scroll up previously when we had our synchronous code we were outputting the grocery item and getting the value of undefined so this is a pattern known as callbacks so I’ll TR a comment here and I’ll say callbacks and for now I will comment it out and paste it so now we will update this and you will use promises so we have our console lock statement saying before and then we have the get grocery item function so rather than calling set timeout as this we can utilize a promise object so A promise is an object that holds the eventual result of an asynchronous operation so we can use the return keyword and I’ll say new promise this accepts two parameters so resolve in the case when it worked successfully and reject in the case when there was an error so this is an arrow function right so a call back we will explore each of these Concepts in more depth throughout this section just wanted to introduce it to you all at once so we moved up the set timeout to be within the Callback function now we can remove call back and rather than saying call back we say resolve because it successfully returns a grocery item so now we have to change how we’re utilizing this so we only need to pass on the ID but we have special methods in order to access the data within the promise so we use a special method which is then which is executed in the case when the promise successfully resolves so we’ll take in the item and we will console log it now we also need a method. catch let’s end this with the parthy in the case when there is an error so if there is an error in the case when it is rejected then this code will run so I’ll say console. error and then the error and that with semicolon so now open up our interor terminal we run this so we see before after and once again this waits for 2 seconds then it returns a promise so we can access the data within that promise with the then method and then we output it to the console right so explore this more in detail in future lessons for now just at a comment I’ll say promise let’s copy this and we’ll build upon it for our next example we’ll comment it out for now now we will cover async away so async away are special keywords allow us to execute this code with cleaner syntax so here we are using the then and catch methods and chaining them in order to access the data that is returned from our promise so we’ll keep our get grocery item function to be the same but we can have different syntax to make this cleaner to read so I can use a special keyword known as async which means that this function contains an asynchronous operation so I’ll name the function display grocery item so we will say grocery item then we’ll use another keyword O8 and then we will specify our function which has the asynchronous operation so in this case the set timeout function then we can simply log it out grocery item so rather than using this syntax and changing the then and do catch methods we can just call display grocery item and pass in the ID of one open up our integrated terminal run it again so we see once again before and after and once this asynchronous operation completes after 2 seconds then we successfully log it to the console let’s do a quick summary first we covered callbacks so these are functions passed as arguments to be executed once an asynchronous operation is complete Rec cover promises which are objects representing the eventual completion or failure of an asynchronous operation and lastly we covered async 08 so this is syntactic suar sugar over promises making asynchronous code look synchronous understanding these patterns is crucial for handling asynchronous operations such as database calls in [Music] JavaScript what are the main methods for handling asynchronous operations in JavaScript and why is it important to understand them the main methods for handling a synchronous oper ations in JavaScript are callbacks promises and async 08 callbacks involve passing a function to be executed after any synchronous operation completes promises represent the eventual completion or failure of an asynchronous task and provides methods like then and catch for handling results a syn8 is built on promises allowing a synchronous code to be written in a more readable synchronous like style understanding these methods is crucial for managing tasks like database calls ensuring efficient and correct code execution how does the asynchronous nature of JavaScript impact the execution order of code and what are the strategies to manage this effectively the asynchronous nature of JavaScript means that code doesn’t always execute in the order it’s written some tasks like iio operations run in the background while the rest of the code continues this can lead to unexpected result results if not managed properly to handle this developers use strategies like callbacks promises and a snle we to control the flow of asynchronous operations ensuring that tasks complete in the desired order and that results are handled correctly so let’s discuss callbacks in more detail first if you look over our example of the incorrect synchronous code where we call a function get grocery item which is utilizing set timeout with a 2-c delay when we output it we get the value undefined because the value is not immediately available so this code mimics trying to get a grocery item from a database but it doesn’t work as intended because the function get grocery item use this set timeout making it asynchronous so the console lock statement executes before the Grocer’s data is available resulting in undefined a call back is a function that is passed as an argument to another function to be executed once an asynchronous operation is complete so let’s go over use callbacks correctly so we have our updated version of the code which utilizes callback so we have our call back parameter and then we invoke it within the asynchronous operation so let’s discuss accessing nested asynchronous data so to handle multiple asynchronous operations such as fetching a user’s grocery list and then fetching the grocery item data you can Nest callbacks so here when we call get grocery item we’re currently just outputting it so let’s say we actually recalling get grocery list this takes in an ID and then a parameter which is a callback function this is an asynchronous operation so we’ll mimic that with the set timeout function pass in our Arrow function which has a 2cond delay I’ll add a comma and I’ll say simulate a call to the database log and I’ll say fetching grocery lists from the database and then we’ll utilize our call back and we’ll pass in the argument which is a JavaScript object representing the grocery list say a property of items which takes it an array so let’s say apple bananas and we’ll say bread so end that with a semic coin let’s update our G grocery item so I can say I’ll say fetching grocery item from I’ll say the grocery list just better to describe what we’re trying to implement here so I’ll say call back and we’ll say the array is apples bananas and bread so now we want to utilize get grocery list so rather than calling get grocery item we say get grocery list this accepts an ID so we’ll say one and then our call back function so it’ll be a grocery list we’ll pass an arrow function so log and I’ll Alpha grocery list comma grocery list so now I will simulate getting the grocery list items and I’ll say get grocery list items grocery list ID and then a callback function containing the items we could output that with items and then outputting that to the console and we’ll end it with a semicolon so this is an example of nested callbacks meaning that you have w a SN operation and once that completes and we have the data that we need then we make another asynchronous call utilizing that data so let’s comment this out save it and then in our integrated terminal up arrow and then run so here we get before and then after then we get fetching the grocery list and then the data that we received and then we call our nested callback function here so fetching a grocery item and we get the items so this demonstrates utilizing nested callback functions so in summary callbacks are functions passed as arguments to be executed once an asynchronous operation is complete properly handling a synchronous code is crucial when dealing with operations like database access which may take some time to [Music] complete why is it important to handle a synchronous operation properly in JavaScript particularly when dealing with tasks like database access handling asynchronous operations properly in JavaScript is crucial because it ensures that tasks like database access which may take time to complete do not block the execution of other code this allows your application to remain responsive efficiently processing multiple tasks without waiting for each one to finish sequentially proper management of a operations such as using callbacks promises or a syn away prevents issues like incomplete data retrieval or unexpected Behavior ensuring that the application functions correctly and smoothly what challenges can arise when using callbacks to manage multiple asynchronous operations and how can these be effectively addressed when using callbacks to manage multiple asynchronous operations challenges like callback hell can arise where nested callbacks make the code difficult to read and maintain this complexity increases the risk of errors and makes debugging harder to address these issues developers can use techniques such as modularizing callback functions or better yet use promises or a sync o08 syntax which allows for more readable and maintainable code by flattening the structure and handling errors more effectively so let’s further discuss nested callback structure in our previous example we use callbacks to handle asynchronous operations so we will expand upon this and we will add another asynchronous operation so we can add that with I’ll name it check item availability this will accept one parameter which is the grocery item and this utilizes the asynchronous method of set timeout pass in our call back and I’ll say checking availability then we can say return true just for Simplicity so if you want to utilize it need to do so within the get grocery item call back so we are dependent on that data this takes in you can say items at the zero index so the first item let’s clean this up a bit so you can clear this and just so we can more easily see our Nest callbacks we’ll remove the outer console log statements so here we see we have get grocery list which is an asynchronous operation once that completes then we call get grocery item which is also a synchronous and then the asynchronous method check item availability so this is simulating making calls to a backend database or a backend API so in this scenario each call back depends on the completion of the previous one resulting in a nested structure this pattern is often referred to as call back hell or the Christmas tree problem because of its shape and complexity so let’s compare this to synchronous code so just as a demonstration of what this would look like if all functions were synchronous right so it would have your log statement same before and then getting the list for get grocery list takes in the ID of the grocery list and then we get the items of the grocery list following get grocery list items say list ID then we’ll check the availability of an item check item availability and we’ll say the first item in the list then we output so log and tab after so this is an example of how clean and easy to read our code would be if it were synchronous however we know that these functions are asynchronous so the data isn’t available immediately there is a delay before we can receive that right let me just add in the 2cond delay to our callback function which I forgot to do so however synchronous code blocks the execution of other operations until the current one finishes which is not ideal for I bound tasks like database queries so let’s discuss the term of call back how we scroll back up so using callbacks for a synchronous code can become difficult to manage and read here we see our nested structure so let’s discuss a simple solution to avoid callback how we can use promises and a syn await syntax so discuss using promises promises provide a cleaner way to handle a synchronous operations so here’s an example for now we will comment how we are utilizing our asynchronous functions and rather than calling set timeout rather we will return a promise right once again A promise is an object that holds the eventual result of an asynchronous operation so we’ll say return new promise and within it it accepts a call back so we’ll say resolve for now we will close that and we can move this up we can move it up with option up Arrow close this so rather than saying call back you can remove that parameter it’s no longer needed and rather we call resolve because it resolved or completed successfully we updated this one to use promises let’s update the other functions return new promise so also accepts callback function will resolve so this here once again option up arrow and within here let’s um do command and then the right bracket better format this code we do the same here so it looks cleaner so once again we removed this call back it’s no longer needed and we call resolve it successfully Returns the grocery items now we have our last one we check availability so once again return new promise tickes in call back function with resolve then option up Arrow to move up in this case it just Returns the value true so in this case we can just say resolve we to say the value of true so now we want to utilize this so for now we can delete this example we had of syn this code and just to demonstrate what we would like the syntax to look like make some space here and now we will utilize these functions that are utilizing promises so we can call get grocery list takes in the value one then get the list and we call get grocery items TI in the list ID then we can change then right so the result of get grocery list item or get grocery item so get the items and we’ll say check item availability items at zero we’ll just say not then we’ll say availability console.log availability and then this value we also include our method or chain our method for catch in case there’s any error console.log actually we do console. eror and then the eror so this is an example of utilizing promises so we use the then method and catch methods so we are rather than having the nested structure we just chain our then methods we can execute this so up arrow and run before and after and there are two second delays as the asynchronous operations complete so everything worked as expected and we have cleaner syntax so let discuss using async AWA so the async AWA syntax built on top of promises further simp simplifies the code So currently and say in get grocery list we are returning a promise let’s say if we’re using the async away keywords so we can mark it as a sync and when we mark it as async we can now utilize the AWA function within it so rather than calling get grocery list and then changing all these methods we’ll create a new method and we can name it display availability we will mark it as a sync so once we mark it then we will utilize the AE keyword within it we’ll wrap it in a TR catch console. air and now we want to utilize these asynchronous operations so because these are asynchronous and they’re returning a promise we can use the await keyword we’ll say list AIT get grocery list pass in the ID then once this data is available then we can call wait get rery item with the list ID right so once this returns right we await this result then we check the availability await check item availability items at zero and then say [Music] console.log Avail ability and then this resolve so rather than utilizing this syntax comment this out and we’ll just call display availability so this function which utilizes the async a keywords is the equivalent of this function call with the chain methods but our code here which utilizes async away looks more similar to synchronous code so it’s easier to read so let’s run this so we see before and after 2C delay and we get our expected result with cleaner syntax so this is the modern way to do it with a SLE we so summary callbacks can lead to nested structures that are difficult to manage promises and asyn we provide cleaner more readable ways to handle asynchronous code what are the benefits of using promises and asyn a weight over callbacks in managing asynchronous operations in JavaScript using promises and a single we in Java JavaScript offers several benefits over callbacks the first being readability promises and Ayn we result in cleaner more linear code that is easier to read and maintain avoiding the nested structure of callbacks otherwise known as callback hell the second benefit is air handling promises provide better air handling through the dock catch method and TR catch blocks with the async aake keywords making it easier to manage asynchronous errors the third benefit is control flow promises and asyn weight allow for more intuitive control flow helping developers manage asynchronous operations more effectively how does the use of promises and a single weight help prevent issues like callback how in JavaScript programming the use of promises and a single weight in JavaScript helps prevent callback how by making a synchronous code more linear and easier to follow promises allow chaining of a synchronous operations with the then method instead of deeply nested callbacks while a snle way further simplifies the syntax making the code look and behave more like synchronous code this reduces complexity improves readability and makes air handling more straightforward resulting in cleaner and more maintainable [Music] code so now let’s discuss name functions so we use name functions to simplify callbacks when dealing with nested callbacks you can replace Anonymous functions with name functions to flatten and simplify the structure of your code this approach makes your code more readable and easier to manage so here’s you can refactor nested callbacks using name functions so implement this from scratch just to ensure that everything makes sense and it’s good to get more practice so once again we have our log statement say before then shift option down arrow after now we Implement our function again get grocery list takes in an ID and a call back so that’s C two parameter variables it accepts then set timeout which is an asynchronous operation the argument takes in is a callback function and here we are simulating a call to the database we can log that out so log out fetching grocery list from the database once again this calls the call back and invokes it pass in the object which is an ID and a name what is say that’s weekly groceries and that with a semicon and there is a 2cond delay so now to help us save some time we can just copy this and paste it and we’ll rename it to be get grocery items so for our console log we’ll say fetching grocery items so for our call back this accepts an array and we’ll just say milk bread and eggs as the data that we pass in once again we can copy this and paste it and we’ll name this to be check item availability so we’ll update our console lock statement which will be checking item availability so for our call back we’ll pass in a JavaScript object which will contain the item and the availability so I’ll say available set to true so now we implemented three asynchronous operations each which have a 2cond delay now in order to actually utilize this we want to have name functions so let’s Implement some functions here and I’ll call this handle grocery items this takes in a list and I’ll call get grocery items the list ID and handle item availability l so not Implement picks in the items and within it this calls check item availability so let’s say the first item and then I’ll pass in call back so display availability so now we need to implement that name function this takes in the availability this outputs to the console availability pasting that here so now I can call get grocery list the ID will be one and then for the call back I’ll say handle grocery item so that will call this function which will call get grocery items and then for the call back is handle item availability then this calls check item availability and then after within it the display availability is called logging to the console we execute this before and after then we get our 2C delays and our expected console outputs so here we see item is not defined let’s see here in checking item availability yeah so for ID it’s supposed to be item run it again now we get our expected output we just need to change the name of that parameter so explanation let’s first discuss name functions by defining name functions let’s scroll up by defining name functions like handle grocery items handle item availability and display availability you can avoid deep nesting and improve the readability of your code let’s discuss passing references note that we are passing references to these functions so this includes handle grocery items handle item availability and display availability instead of calling them directly so what are the advantages the first is readability the code is easier to read and understand the second Advantage is reusability name functions can be reused elsewhere in the code if needed limitations while using name functions helps it’s not the most efficient way to handle asynchronous code for better approach consider using promises so using promises promises provide a cleaner more manageable way to handle asynchronous operations compared to nested callbacks so here you can convert the above example to use promises so here for each of these functions that we implemented we want to call return new promise this object takes in the call back so resolve then we just move this up option up arrow and then instead of call back we just call resolve we can remove call back parameter we just repeat this so return new promise Pi in and resolve move that up option up Arrow save that and one last time oh yeah you can have to remove the call back parameter and then call result then last time we get return new promise takes in resolve and we move this up save that and we call resolve here now in order to utilize that we will no longer be calling or invoking it like that rather we will call get grocery list passing in the ID of one and then we have our methods then and catch so we chain these methods list so I know we did cover this before but repetition is very good especially if this is the first time that you are going over promises so then items and we’ll call check item availability which is the first item in the list do then say availability console.log availability and then this parameter variable then we end it with catch so we path in the error to one urse console. error and then the eror end it with a su icon so now we execute this code which is utilizing promises as opposed to callback functions we have before and after and then 2 second delays for our expected console output now we get cleaner syntax without having to pass all these references to all these functions we created so using promises makes the code more straightforward and easier to handle especially as the complexity of asynchronous operations [Music] increases how can ref factoring nested callbacks into name functions improve the readability and maintainability of asynchronous code in JavaScript refactoring nested callbacks into name functions improves the readability and maintainability of asynchronous Code by reducing complexity and avoiding deeply nested structures known as callback how name functions makes the code more organize easier to follow and allows for better reuse of code this approach simplifies debugging and understanding the flow of asynchronous operations making it easier to manage and maintain the code base as the application grows in complexity what are the limitations of using name functions for handling asynchronous operations and how do promises provide a more efficient solution the limitations of using name functions for handling asynchronous operations include increased complexity when dealing with multiple asynchronous task and a tendency to create deeply nested structures while name functions improve readability they don’t fully resolve the issue of callback how promises provide a more efficient Solution by allowing for a more linear and manageable flow of asynchronous tasks through chaining which improves readability and simplifies air handling leading to cleaner and more maintainable code so let’s discuss promises JavaScript promises are a powerful tool for managing asynchronous operations A promise is an object that represents the eventual result of an asynchronous operation it can be in one of three states the first being pending so this is the initial State when the promise is still waiting for the asynchronous operation to complete the second state is fulfilled the operation completed successfully and the promise has a value and the third possible state is rejected so the operation failed and the promise hasn’t air so Crea a promise to create a promise you can use the promise Constructor which takes a function with two parameters resolve and reject and these parameters are functions used to indicate the completion of the asynchronous operation either successfully which would be the case when it resolves or unsuccessfully in the case when it rejects so to demonstrate this say cons B and then new promise this takes in a call back so resolve and reject our Arrow function syntax then we can start in a synchronous operation such as accessing a database or calling a web service so if the operation is successful then we call resolve with the result if the operation fails then we call reject with an error so in the first case we’ll say resolve to demonstrate an example of a successful operation so output value of P and we run this we get the promise with the value of one better yet do then so we’ll say result console.log the result and we’ll just chain these methods actually so do catch error console. eror passing in that eror object so we run this again and we get the value of one which is the value that was passed in when we resolved this promise likewise if we were to call reject we pass in an error so I can say new error and I’ll say erir message in the case of a failed operation we execute this and we get our expected error message so let’s discuss consuming a promise so once you have a promise you can use theben and do catch method as we did to handle the result or the error let’s go over an example of handling errors so we’ll update this example to simulate an a synchronous operation that failed so we can call set timeout pass in call back and we’ll say it has a 2cond delay let’s move this up so option an up Arrow so now when we do this let’s update this to be console.log and we will log out the message of the air right so in this case it would be air message so now when we run this and integrated terminal command J up arrow and run there’s a 2C delay and then we get the airor message so in summary a promise starts in the pending state it transitions to fulfilled if the asynchronous operation complete successfully it transitions to rejected if the operation fails we use the DOT then method to handle the successful result and we use the catch method to handle errors finally let’s discuss best practices whenever you have an asynchronous function that takes a call back consider modifying it to return a promise for better readability and maintainability this approach helps avoid callback hell and makes the code easier to follow how do promises improve the management of asynchronous operations in JavaScript particularly compared to traditional callback methods promises improve the management of asynchronous operations in JavaScript by providing a more structured and readable way to handle tasks compared to traditional callbacks they allow you to chain operations like then for success and catch for errors handling callback hell and making the code easier to follow promises also offer better air handling and simplify the process of managing multiple asynchronous operations leading to cleaner and more maintainable code why is it beneficial to modify asynchronous operations that use callbacks to return promises instead and how does this practice enhance code readability and maintainability modifying asynchronous functions to return promises instead of using callbacks is beneficial because it simplifies the code structure making it more readable and easier to maintain promises allow for chaining operations and handling errors more cleanly with then and catch methods reducing the complexity associated with nested callbacks known as callback H this approach leads to more organized and modular code which is easier to debug and scale as your application grows so let’s discuss resolving callback outl by using promises so in this code that we wrote in a previous lesson this demonstrates nested callbacks also known as callback how which can make your code difficult to read and maintain so here in this case we have three asynchronous methods and they depend on each other so these run one after another now you can imagine if we had to perform other asynchronous operations then we will continue to have to indent and continue to Nest these callbacks so this video is just a reminder that we want to utilize promises when working with asynchronous code we we do this to improve the readability and maintainability of our code base so in this case instead of utilizing callbacks we are returning a promise right once again A promise is an object that holds the eventual result of any synchronous operation and then we can utilize the built-in methods so then and catch to chain these methods and work with the asynchronous data this approach makes the code more linear and easier to read eliminating the Deep nesting associated with callback how so in summary promises these are objects representing the eventual completion or failure of an asynchronous operation now these promises can be in different states so promises can be in one of three states so it can be pending fulfilled or rejected so methods that promises have include the then method to handle resolve values and catch to handle errors and lastly converting call back based functions to return promises can significantly improve code readability and maintainability how do promises help in resolving the challenges of callback how in a synchronous JavaScript programming promises help resolve the challenges of callback how and asynchronous JavaScript programming by allowing you to chain asynchronous operations in a more linear and readable manner instead of deeply nesting callbacks promises use then and catch methods to handle sucess sucess and errors respectively this flattens the code structure making it easier to understand maintain and debug by converting callback based functions to return promises developers can write cleaner more manageable code while avoiding the complexity and pitfalls of nested callbacks what are the key benefits of converting callback based functions to return promises particularly in terms of code readability and maintainability converting callback based functions to return promises offers key benefits in terms of code readability and maintainability Promises allow for chaining operations using then and catch which results in a flatter more linear code structure making it easier to read and understand this approach eliminates the deeply nested hardto manage code typical of callbacks known as callback how additionally promises provide a consistent way to handle errors further enhancing the maintainability of the code [Music] base so let’s go over creating subtle promises sometimes you might need to create a promise that is already resolved this can be particularly useful for unit testing where you need to simulate a successful asynchronous operation such as a web service call to create a resolve promise you can use the promise. resolve method which returns a promise that is already resolved so we can create a new file here from the command line I’ll say touch prom api.js so we can go into this new file that we created and then we can call comp P assign to promise do resolve we’ll pass in an object so in this case it will have a property of ID the value one and then to access this value we use the then method and we pass in a call back so we’ll get the result and we’ll just output that right output in the result open up the integrated terminal with command J or control J and then we will run node promise api.js and here we get the expected resolve value so this code snippet creates a resol promise with an object containing ID of one and logs the result to the console now let’s go over creating rejected promises similarly you might need to create a promise that is already rejected for instance to simulate a failed asynchronous operation in a unit test you can use the promise. reject method to create a rejected promise so we can close this out so command J and we’ll update this to instead use reject and then for the argument we pass in a new erir object so new error and then the message will be reason for rejection and three dots so now it’s p. pen we can call do cach in this case we can do error console.log and I can say error. message so because we are expecting an error or the rejection rather we just include the cach method right so we remove the then method so let’s run this and we’re expecting the error message reason for rejection say for rejection so this creates a rejected promise with an airor message and we log the air to the console so in summary resolve promises use the promise. resolve and then pass in the value to create a promise that is already resolved and for rejected promises use promise. reject and passed in an air object to create a promise that is already rejected these methods are useful for simulating different scenarios in unit tests or when you need immediate resolution or rejection of promises these methods are useful for simulating different scenarios in unit tests or when you need immediate resolution or rejection of promises how can creating resolved and rejected promises with methods like promise. resolve and promise. reject be useful in testing and simulating asynchronous operations creating resolved and rejected promises with methods like promise. resolve and promise. reject is useful in testing and simulating asynchronous operations
because they allow developers to immediately generate success or failure outcomes without needing to perform actual asynchronous task this capability is particularly valuable in unit testing where you may want to test how your code handles resolved or rejected promises such as simulating successful API responses or air conditions ensuring your code behaves correctly in different [Music] scenarios so let’s discuss running multiple asynchronous operations in parallel sometimes you need to run several asynchronous operations simultaneously and perform an action once all of them have completed for example you might call different apis like Facebook and Twitter or X and once both calls finish you return the result to the client let’s go over an example of this so we’ll have a simulation I’ll say simulation for calling Facebook API so I’ll say cons and I’ll say P1 for the first promise new promise so we know this takes in a callback takes resolve as the first parameter and within it we’ll have set timeout as our asynchronous operation this also takes a call back and we’ll say the delay is 2 seconds right so 2,000 milliseconds then we will log a say async operation Three Dots and then resolve with the value one and then we’ll have a simulation we’re calling the Twitter or X API so we’re can actually just copy this because it’ll be the same syntax just to change it to be P2 to represent the second promise I’ll say a sync operation 2 and I’ll say syn operation one just so we can differentiate these console statements so now I’ll say running both a synchronous operations let’s scroll up so we can see it better I can say promise.all and then I’ll pass it an array containing both of these promises so P1 and P2 now I’ll call then sixes s the result and I will console log the result and I also do. catch let me remove the semicolon so this takes in an err console.log and I’ll say airor air. message now we can end that with the semicon so this code kicks off two asynchronous operations and uses promise.all to wait until both promises are resolved the then method is called with the results when both operations complete so let’s execute this so command J control J and then node index.js so once both of them are completed then we see async operation one async operations 2 and then you see the two values that they return that they resolve to let me update this to be two I’ll run it again so once again we get the expected out so now let’s discuss handling promise rejections if one of the promises fail then promise.all will reject in the catch method will handle the error so if any one of them reject then the catch method will be executed so you can say for example rather than this being resolved we’ll specify the second parameter of reject and we will invoke that so this operation failed we can run that so here we see the error with the value of undefined so rather than passing one let pass in new error and I’ll say async operation one failed right for a descriptive error message rather than just the value one now we got our expected error message so in this example if P1 right the first promise right the simulation for calling the Facebook API if that fails then the entire promise.all will reject and the error will be logged so’s discuss using promise. race if you need to proceed as soon as possible as one of the promises is fulfilled or rejected you can use promise. race so rather than promise at all we can do promise. rce and in this case with promise. race the first promise to resolve or reject will determine the outcome if it resolves first the then method will be called with the result of the first fulfilled promise if it rejects first the catch method will handle the error so we can see an example of this let’s run it again so in this case the P1 rejected before the second operation likewise let’s say if I do comment this out and if I say resolve with the value one so once again promise. raise will resol or reject based on the first outcome so here we see for the result was the value of one as the async operation one completed first so in summary with promise. all this waits for all promises to resolve if any promise rejects the entire promise is rejected with promise. race this resolves or rejects as soon as one promise resolves or rejects these methods help manage multiple asynchronous operations effectively ensuring that your code is cleaner and more maintainable [Music] what are the advantages of using promise.all and promise. R for handling multiple asynchronous operations in JavaScript promise.all allows you to run multiple asynchronous operations in parallel and waits for all of them to complete before proceeding it’s useful when you need all tasks to finish successfully before taking the next step if any promise fails the entire operation fails so with promise. Ray it resolves or rejects as soon as one of the promises completes making it useful when you want to proceed based on whichever task finishes first this approach can help optimize performance when only the quickest result is needed how can managing multiple asynchronous operations with promises enhance the efficiency and readability of JavaScript applications managing multiple asynchronous operations with promises enhances the efficiency and reliability of JavaScript applications by allowing tasks to run concurrently reducing weight times with promis at all this ensures that all tasks complete successfully before proceeding making the application reliable when multiple results are needed with promise. rce this allows the application to respond Faster by acting on the first completed task improving performance in scenarios where the quickest result is prioritized these tools help structure and control complex asynchronous workflows leading to cleaner more maintainable code so let’s go over simplifying our asynchronous code with the async await keywords javascript’s async and await features provide a more readable and straightforward way to write a synchronous code resembling synchronous code so here’s an example using promises that we did in a previous lesson so here we see we have three functions which use an asynchronous operation so each of them are using set timeout and each of them return a promise so to utilize these and to get access to the result of the synchronous operation we use the then methods in order to access the data and we chain the methods now we can also implement this using the async away keywords so rather than doing it like this I can Implement a function and I’ll use the async keyword we can name this display item availability so we can say con list now we use the await keyword to await the result of the asynchronous operation we we call get grocery list we’ll pass in the ID of one then we’ll get the items say a wait get grocery items we’ll say list. name see yep so the name of the list then we’ll get the availability the await keyword check item availability so the first item in the list and then we’ll output availability and then we output the result of that so now let’s comment this out for now and we’ll just invoke this method so now if we were to execute this file need to change into the correct directory that would be nine I can run so here I get the output of after then fetching grocery list from the database fetching the grocery items and then the availability of the item so an explanation of this code we use the await keyword so this keyword allows you to wait for a promise to resolve and get its result you could use it only inside functions marked with the async keyword so let’s discuss async this keyword is used to declare that a function is asynchronous it ensures that the function returns a promise when using await the JavaScript engine pauses the execution of the function until the promise settles this makes the asynchronous code look like synchronous code which is easier to read and understand so handling errors with Ayn away in the promise based approach the catch method is used to handle errors and with a SN away you use a tri catch block so once again again we update this so I’ll say try let’s highlight all this and we’ll do option up Arrow to move it up then we can say catch air and then we can log this err out so that would be air do colon air. message better format this and then we save it so in summary asyn and wa provides a cleaner way to write a synchronous code that looks like synchronous code for for air handling we use try and catch blocks to handle errors when using a sync and a we using a sync and a we can make your asynchronous JavaScript code much more readable and easier to maintain this syntactic sugar over promises simplifies the code structure [Music] significantly how do the async and aw keywords simplify the process of writing and understanding a synchronous code in JavaScript the async and awake keywords simplify writing a synchronous code in JavaScript by making it look and behave like synchronous code async marks the function as asynchronous automatically returning a promise while await pauses the function’s execution until the promise resolves this eliminates the need for complex promise chains and nesting resulting in more readable maintainable and easier to understand code especially when dealing with multiple asynchronous operations what are the benefits of using a syn and a weight for a handling and a synchronous JavaScript code compared to traditional promise-based methods using async and a weight for error handling and JavaScript provides a more straightforward and readable approach compared to traditional promise-based methods with a SN in away you can handle errors using try and catch blocks which are familiar with synchronous code making it easier to understand and manage this approach of avoids the need for chaining catch methods resulting in cleaner code that is easier to debug and maintain especially in complex asynchronous [Music] workflows so let’s summarize what we covered in this section so this section was about synchronous versus asynchronous code understanding the difference between synchronous and asynchronous code is fundamental in JavaScript synchronous code executes sequentially blocking further execution until the current task is completed in contrast a synchronous code allows other operations to continue while waiting for an asynchronous task to complete improving performance and responsiveness let’s go over the patterns for dealing with asynchronous code JavaScript offers several patterns to manage asynchronous operations the first being callbacks these are functions passed as arguments to other functions to be invoked once an asynchronous operation is complete the second pattern is promises these are objects representing the eventual completion or failure of an a synchronous operation providing a cleaner way to handle a synchronous Logic the third pattern is a synon away this a syntax that makes a synchronous code appear synchronous enhancing readability let’s go over callbacks callbacks were the original method for handling a synchronous code in JavaScript they involve passing a function to another function to be executed after an operation completes so let’s talk about the concept of callback how these are nested callbacks which can lead to callback how which is a situation where code becomes deeply nested and difficult to manage this pattern complicates both reading and maintaining the code named functions to mitigate callback out name functions can be used to flatten the structure instead of nesting asynchronous functions you Define separate name functions and pass them as callbacks promises promises provide a more manageable alternative to callbacks a promise represents an operation that hasn’t completed yet but is expected in the future promises have three states pending fulfilled and rejected replacing callbacks with promises promises help avoid the complexity of nested callbacks by returning promises from functions you can chain asynchronous operations more straightforward using the them method for resolve promises and do catch for errors consuming promises consuming promises involves using the themm method to handle resolve values and do catch to handle errors this approach results in a more readable and maintainable code base creating subtle promises JavaScript provides promise. resolve and promise. reject methods to create promises that are already settled either fulfilled or rejected this is particularly useful in testing scenarios running promises in parallel using promise. all multiple promises can be executed in parallel and you can perform an action when all of them are resolved if any promise is rejected the entire promise. all is rejected async and a wa async and a wa keywords provide a way to write a synchronous code that look synchronous functions declared with a sync return a promise and a wait pauses the execution of the function until the promise is resolved or rejected making the code easier to read and maintain error handling is done using try and catch blocks by understanding and applying these patterns you can effectively manage asynchronous operations in JavaScript leading to more efficient and maintainable code
Affiliate Disclosure: This blog may contain affiliate links, which means I may earn a small commission if you click on the link and make a purchase. This comes at no additional cost to you. I only recommend products or services that I believe will add value to my readers. Your support helps keep this blog running and allows me to continue providing you with quality content. Thank you for your support!
This tutorial serves as a guide for JavaScript beginners, aiming to impart foundational knowledge for creating dynamic web pages and applications. It begins with an introduction to JavaScript’s core concepts, including its syntax, how to enable it in browsers, and where to place code within HTML. The text then progresses to cover essential programming elements such as variables, data types, operators, control flow statements (like if-else and loops), and functions. Furthermore, the tutorial explores JavaScript objects, including built-in types like Number, String, and Array, as well as concepts like events and browser interactions. Finally, it touches upon more advanced topics such as error handling, form validation, and debugging, providing a comprehensive overview for newcomers to the language.
What are two key characteristics of JavaScript as a programming language, and for what primary purpose was it designed?
Explain the concept of client-side JavaScript and provide one advantage it offers over traditional server-side scripting.
Describe two limitations of client-side JavaScript that prevent it from being considered a full-fledged general-purpose programming language.
What are the standard HTML tags used to embed JavaScript code within a web page, and what are the recommended values for their key attributes?
Explain the significance of the var keyword in JavaScript and describe the difference between declaring and initializing a variable.
What are the two primary scopes of variables in JavaScript, and how does JavaScript handle variable names that exist in both scopes within a function?
Provide three examples of arithmetic operators in JavaScript and briefly explain their function.
Describe the purpose of comparison operators in JavaScript and give an example of a comparison that would evaluate to false if variable x holds the value 5 and variable y holds the value 10.
Explain the functionality of the logical AND (&&) operator in JavaScript. Under what condition will an expression using this operator evaluate to true?
What is the purpose of JavaScript events, and can you provide an example of a common HTML event and how it might be used with JavaScript?
Quiz Answer Key
JavaScript is a lightweight, interpreted programming language. It was primarily designed for creating network-centric applications and enhancing web pages with dynamic and interactive elements.
Client-side JavaScript is JavaScript code that is executed by the user’s web browser, rather than on a web server. One advantage is less server interaction, as user input can be validated in the browser before being sent to the server.
Two limitations of client-side JavaScript are its inability to read or write files (for security reasons) and its lack of built-in support for networking applications or multithreading/multiprocessing.
The standard HTML tags for embedding JavaScript are <script> and </script>. The recommended attribute to specify the scripting language is type with the value “text/javascript”. The language attribute is considered phased out in recent HTML versions.
The var keyword is used to declare variables in JavaScript, essentially creating a named container in memory. Declaration is simply stating the variable name (e.g., var myVariable;), while initialization is assigning an initial value to the variable (e.g., var myVariable = 10;).
The two primary scopes are global scope (variables defined anywhere in the code) and local scope (variables defined within a function). Within a function, a local variable with the same name as a global variable takes precedence, effectively hiding the global variable.
Examples of arithmetic operators include + (addition), – (subtraction), and * (multiplication). The addition operator adds two operands, the subtraction operator subtracts the second operand from the first, and the multiplication operator multiplies both operands.
Comparison operators in JavaScript are used to compare the values of two operands and return a Boolean value (true or false) based on the comparison. For example, (x > y) where x is 5 and y is 10 would evaluate to false.
The logical AND (&&) operator evaluates to true only if both of its operands (the expressions on either side of the operator) evaluate to true. If either operand is false, the entire expression will be false.
JavaScript events are actions or occurrences that happen in the browser, such as a user clicking a button or a page finishing loading. A common HTML event is onclick, which can be used to execute a JavaScript function when a user clicks on an HTML element.
Essay Format Questions
Discuss the advantages and limitations of using JavaScript for web development, considering its client-side nature and its integration with HTML. How has the evolution of web technologies addressed some of these limitations?
Explain the significance of variable scope in JavaScript, differentiating between global and local variables. Provide scenarios where understanding variable scope is crucial for avoiding errors and maintaining code functionality.
Compare and contrast the different types of operators available in JavaScript (arithmetic, comparison, logical, assignment). Provide examples of how each type of operator contributes to the functionality of a JavaScript program.
Describe the different ways JavaScript code can be placed within an HTML document, including the advantages and potential disadvantages of each method. When might you choose one placement method over another?
Discuss the fundamental data types supported by JavaScript. How does JavaScript’s handling of data types differ from strictly typed languages, and what are the implications of this dynamic typing?
Glossary of Key Terms
Interpreted Language: A programming language where the code is executed line by line by an interpreter, without the need for prior compilation into machine code.
Client-Side Scripting: Code that is executed by the user’s web browser, as opposed to being run on a web server.
Syntax: The set of rules that define the structure of a programming language, including how statements are written and organized.
Variable: A named storage location in a computer’s memory that can hold a value.
Declaration: The act of introducing a variable name to the program, indicating that a storage location will be used for that name.
Initialization: The act of assigning an initial value to a variable at the time of its creation or later in the program.
Scope: The region of a program where a particular variable can be accessed.
Global Variable: A variable that is declared outside of any function and can be accessed from any part of the JavaScript code.
Local Variable: A variable that is declared inside a function and can only be accessed within that function.
Operator: A symbol or keyword that performs an operation on one or more operands (values or variables).
Operand: A value or variable that an operator acts upon.
Arithmetic Operator: A symbol that performs mathematical calculations (e.g., addition, subtraction, multiplication).
Comparison Operator: A symbol that compares two operands and returns a Boolean value based on the relationship between them (e.g., equal to, greater than).
Logical Operator: A symbol that performs Boolean logic operations on one or more Boolean operands (e.g., AND, OR, NOT).
Assignment Operator: A symbol that assigns a value to a variable (e.g., =, +=).
Event: An action or occurrence that happens in the browser, such as a user interaction (e.g., clicking a button) or a browser process (e.g., page loading).
JavaScript Tutorial Briefing Document
Date: October 26, 2023 Source: Excerpts from “javascript_tutorial.pdf” (Tutorials Point, Copyright 2015)
Overview:
This document provides a briefing on the fundamental concepts of JavaScript as presented in the initial sections of the “javascript_tutorial.pdf”. The tutorial is designed for beginners with prior knowledge of HTML and some exposure to object-oriented programming and online application creation. It covers the basics of the language, including its nature, syntax, how to enable it in browsers, placement within HTML, fundamental data types, variables, operators, control flow statements (if-else, switch-case, loops), functions, events, cookies, page redirection, dialog boxes, the void keyword, and page printing. The document also introduces JavaScript objects and their basic properties and methods, including built-in objects like Number, Boolean, String, Array, Date, Math, and RegExp, as well as the Document Object Model (DOM). Finally, it touches upon advanced topics like errors and exceptions, form validation, animation, multimedia, debugging, image maps, and browser-specific information.
Part 1: JavaScript Basics
This section lays the groundwork for understanding JavaScript.
What is JavaScript? JavaScript is described as a “lightweight, interpreted programming language” primarily used for creating “network-centric applications” and adding interactivity to web pages. It is highlighted as “complimentary to and integrated with Java” and “HTML“, as well as being “open and cross-platform.” Its history is briefly mentioned, noting its initial name as LiveScript and its introduction in Netscape 2.0 in 1995. The importance of the ECMA-262 Specification for standardizing the core language is also noted.
Client-Side JavaScript: The tutorial emphasizes that client-side JavaScript, embedded in or referenced by HTML documents, is the most common form. It allows web pages to be dynamic, interact with users, control browsers, and dynamically create HTML content. Advantages over server-side scripts include “less server interaction“, “immediate feedback to the visitors“, “increased interactivity“, and “richer interfaces.” Limitations include the inability to read or write files (for security), lack of networking application support, and no multithreading or multiprocessor capabilities.
JavaScript Development Tools: The tutorial points out that JavaScript doesn’t require expensive tools, with a simple text editor being sufficient. Several more advanced editors like Microsoft FrontPage, Macromedia Dreamweaver MX, and Macromedia HomeSite 5 are also mentioned.
Where is JavaScript Today? The tutorial mentions ECMAScript Edition 5 as a significant update and notes that JavaScript 2.0 conforms to this standard with minor differences. It states that Netscape’s JavaScript and Microsoft’s JScript align with the ECMAScript standard while still supporting non-standard features.
JavaScript Syntax: JavaScript code is placed within <script>…</script> HTML tags. The <script> tag can be placed anywhere but is “normally recommended” within the <head> tags. Important attributes of the <script> tag are language (though phased out, typically “javascript”) and type (recommended, set to “text/javascript”). A basic “Hello World” example using document.write() is provided, along with the use of HTML comments (<!– … //–>) to handle browsers without JavaScript support, where // within the comment prevents the closing HTML comment tag from being interpreted as JavaScript. The tutorial clarifies that “JavaScript ignores spaces, tabs, and newlines” and that “Semicolons are Optional” if statements are on separate lines, although using them is good practice. Importantly, “JavaScript is a case-sensitive language.” Both // (single-line) and /* … */ (multi-line) comments are supported, and <!– is treated as a single-line JavaScript comment, with //–> being the recommended way to close an HTML comment containing JavaScript.
JavaScript Enabling: The tutorial provides step-by-step instructions on how to enable or disable JavaScript in various popular browsers: Internet Explorer, Firefox, Chrome, and Opera. The use of <noscript> tags to display a warning message to users with JavaScript disabled is also explained. For example:
<noscript>
Sorry…JavaScript is needed to go ahead.
</noscript>
JavaScript Placement: The tutorial details four ways to include JavaScript in HTML: within the <head>, within the <body>, in both <head> and <body>, and in an external .js file included using the src attribute of the <script> tag. Placing scripts in the <head> is suggested for scripts that run on events, while placing them in the <body> is for scripts that generate content on page load. External files (<script type=”text/javascript” src=”filename.js” ></script>) are recommended for reusing identical JavaScript code across multiple pages.
JavaScript Variables: JavaScript supports three primitive data types: “Numbers, e.g., 123, 120.50 etc.“, “Strings of text, e.g. ‘This text string’ etc.“, and “Boolean, e.g. true or false.“. It also defines trivial types null and undefined, and a composite type object. All numbers are treated as 64-bit floating-point values. Variables are declared using the var keyword (var money;, var money, name;). Initialization can occur at declaration or later (var name = “Ali”;, money = 2000.50;). Re-declaration of variables with the same name using var should be avoided. JavaScript is an “untyped language“, meaning a variable can hold any data type, and the type can change during execution. Variable scope is either global (defined anywhere) or local (visible only within a function). Local variables take precedence over global variables with the same name within a function. Rules for variable names include: no JavaScript reserved keywords, must not start with a numeral, must begin with a letter or underscore, and are case-sensitive. A comprehensive list of JavaScript reserved words is provided.
JavaScript Operators: An operator is defined as a symbol that performs an operation on operands (e.g., in 4 + 5 = 9, + is the operator, and 4 and 5 are operands). The tutorial covers arithmetic operators (+, -, *, /, %, ++, –, noting that + can also concatenate strings), comparison operators (==, !=, >, <, >=, <=), logical operators (&&, ||, !), bitwise operators (&, |, ^, ~, <<, >>, >>>), assignment operators (=, +=, -=, *=, /=, %=, and their bitwise counterparts), and miscellaneous operators, specifically the conditional (ternary) operator (? 🙂 and the typeof operator. The typeof operator returns a string indicating the data type of its operand (e.g., “number”, “string”, “boolean”, “object”, “function”, “undefined”). Examples are provided for each operator type. For instance, regarding the conditional operator:
result = (a > b) ? 100 : 200;
This assigns 100 to result if a is greater than b, and 200 otherwise.
Part 2: JavaScript Objects
This section introduces the concept of objects in JavaScript.
JavaScript Objects: An object is a collection of properties (named values) and methods (functions that can be performed on the object). The tutorial covers user-defined objects, defining methods for objects, and the use of the with keyword (though often discouraged).
Built-in Objects: The tutorial then delves into various built-in JavaScript objects, detailing their properties and methods with examples:
Number: Properties like MAX_VALUE, MIN_VALUE, NaN, NEGATIVE_INFINITY, POSITIVE_INFINITY, prototype, constructor, and methods like toExponential(), toFixed(), toLocaleString(), toPrecision(), toString(), valueOf().
Boolean: Properties constructor, prototype, and methods toSource(), toString(), valueOf().
String: Properties constructor, length, prototype, and numerous methods for string manipulation (e.g., charAt(), charCodeAt(), concat(), indexOf(), lastIndexOf(), slice(), split(), replace(), search(), toLowerCase(), toUpperCase(), etc.) and HTML wrappers (e.g., anchor(), bold(), italics(), link()).
Date: Properties constructor, prototype, various methods for getting and setting date and time components (e.g., getDate(), getDay(), getFullYear(), getHours(), setDate(), setFullYear(), setHours(), getTime(), setTime(), and their UTC counterparts), as well as methods for converting dates to string formats (e.g., toDateString(), toGMTString(), toLocaleDateString(), toString(), toTimeString(), toUTCString(), valueOf()). Static methods Date.parse() and Date.UTC() are also covered.
Math: Properties for mathematical constants (e.g., Math.E, Math.PI, Math.LN2, Math.LOG2E, Math.SQRT2) and a wide range of mathematical functions as methods (e.g., abs(), acos(), asin(), atan(), ceil(), cos(), exp(), floor(), log(), max(), min(), pow(), random(), round(), sin(), sqrt(), tan()).
RegExp: Covers regular expressions, including brackets, quantifiers, literal characters, metacharacters, and modifiers. Properties like constructor, global, ignoreCase, lastIndex, multiline, source, and methods exec(), test(), toSource(), toString().
DOM (Document Object Model): Briefly introduces the DOM, mentioning “The Legacy DOM”, “The W3C DOM”, and “The IE 4 DOM”, as well as “DOM Compatibility”.
Part 3: JavaScript Advanced
This section touches upon more advanced JavaScript concepts.
Errors and Exceptions: Discusses syntax errors, runtime errors, and logical errors. It introduces the try…catch…finally statement for error handling, the throw statement for raising custom exceptions, and the onerror() method.
Form Validation: Covers basic and data format validation techniques in JavaScript to ensure user input is correct before submission.
Animation: Introduces manual and automated animation techniques using JavaScript, including rollover effects with mouse events.
Multimedia: Briefly mentions checking for browser plug-ins and controlling multimedia elements using JavaScript.
Debugging: Provides information on error messages in different browsers (IE, Firefox/Mozilla), error notifications, and general tips for debugging JavaScript code.
Image Map: Covers the implementation of image maps using JavaScript.
Browsers: Discusses the navigator object and its properties (e.g., appName, appVersion, userAgent) and methods, as well as techniques for browser detection.
Key Themes and Important Ideas:
JavaScript as a Client-Side Scripting Language: The primary role of JavaScript is to enhance HTML and create dynamic and interactive web pages by running in the user’s browser.
Ease of Implementation: JavaScript is presented as easy to start with, requiring just a text editor and a web browser.
Integration with HTML: JavaScript code is embedded within HTML using <script> tags, allowing for close interaction between the structure and behavior of a web page.
Fundamental Programming Concepts: The tutorial covers core programming concepts like variables, data types, operators, control flow statements (conditionals and loops), and functions, providing a foundation for writing more complex scripts.
Object-Oriented Capabilities: While described as interpreted, JavaScript is also highlighted as having object-oriented capabilities, with the introduction of objects, properties, and methods.
Built-in Functionality: JavaScript provides a rich set of built-in objects (Number, Boolean, String, Array, Date, Math, RegExp) with numerous properties and methods that simplify common programming tasks.
Event Handling: JavaScript enables the creation of interactive web pages by allowing scripts to respond to user-initiated events (e.g., onclick, onsubmit, onmouseover).
Browser Interaction: JavaScript can interact with the browser environment, including handling cookies, performing page redirects and refreshes, and displaying dialog boxes.
Error Handling and Validation: The tutorial introduces mechanisms for handling errors and validating user input, crucial for creating robust web applications.
Quotes:
“JavaScript is a lightweight, interpreted programming language.” (About the Tutorial, p. i)
“Designed for creating network-centric applications.” (About the Tutorial, p. i)
“It is complimentary to and integrated with Java.” (About the Tutorial, p. i)
“It is complimentary to and integrated with HTML.” (About the Tutorial, p. i)
“Client-side JavaScript is the most common form of the language. The script should be included in or referenced by an HTML document for the code to be interpreted by the browser.” (JAVASCRIPT – Overview, p. 11)
“You can place the
Understanding JavaScript Fundamentals and Web Browser Integration
What is JavaScript and what are its key characteristics?
JavaScript is a lightweight, interpreted programming language primarily designed for creating network-centric applications. It’s known for being easy to implement due to its integration with HTML, and it’s an open and cross-platform language. It allows for client-side scripting to create dynamic and interactive web pages.
Who is the intended audience for this tutorial and what prior knowledge is expected?
This tutorial is designed for JavaScript beginners who want to understand the fundamental functionalities of JavaScript to build dynamic web pages and web applications. It assumes that the reader has prior knowledge of HTML coding and some exposure to object-oriented programming concepts and creating online applications.
What are some of the advantages of using client-side JavaScript in web development?
Client-side JavaScript offers several benefits, including reduced server interaction by enabling input validation before submission, immediate feedback to users without page reloads, increased interactivity through features like mouse hover effects, and richer user interfaces with elements like drag-and-drop components.
What are some limitations of JavaScript that prevent it from being considered a full-fledged programming language?
Despite its capabilities, client-side JavaScript has limitations. For security reasons, it cannot read or write files. It also lacks built-in support for networking applications and does not have multithreading or multiprocessor capabilities.
How is JavaScript typically included and placed within an HTML document?
JavaScript code is included within HTML documents using the <script> tags. These tags can be placed in the <head>, the <body>, or both sections of the HTML. Additionally, JavaScript code can be stored in an external .js file and linked to the HTML document using the src attribute of the <script> tag. It is often recommended to place script tags in the <head> for scripts that run on events or in the <body> for scripts that generate content on page load.
What are variables in JavaScript and what are the rules for naming them?
In JavaScript, variables are named containers used to store data. Before using a variable, it must be declared using the var keyword (though modern JavaScript introduces let and const). Variable names must not be JavaScript reserved keywords, should not start with a numeral, must begin with a letter or an underscore, and are case-sensitive.
What are the different types of operators available in JavaScript and what are their basic functionalities?
JavaScript supports various types of operators, including:
Bitwise Operators: Perform operations on the binary representations of numbers (e.g., &, |, ^, ~, <<, >>, >>>).
Miscellaneous Operators: Include the conditional (ternary) operator ?: and the typeof operator to determine the data type of a variable.
How can users enable or disable JavaScript support in common web browsers like Internet Explorer, Firefox, and Chrome?
The tutorial provides step-by-step instructions for enabling and disabling JavaScript in Internet Explorer (via Internet Options > Security > Custom Level > Scripting > Active scripting), Firefox (by toggling the javascript.enabled setting in about:config), Chrome (via Settings > Show advanced settings > Content settings > Javascript), and Opera (via Tools > Preferences > Advanced > Content > Enable JavaScript). It also mentions using the <noscript> tag to display a warning to users with JavaScript disabled.
JavaScript Basics: A Beginner’s Guide
Let’s discuss JavaScript Basics based on the provided tutorial.
What is JavaScript? JavaScript is described as a lightweight, interpreted programming language. It is designed for creating network-centric applications and is commonly used as part of web pages to enable client-side scripts that can interact with the user and create dynamic pages. JavaScript has object-oriented capabilities and is complementary to and integrated with Java and HTML. It is also considered open and cross-platform and very easy to implement because it is integrated with HTML. It was initially known as LiveScript but was renamed JavaScript by Netscape, possibly due to the popularity of Java. JavaScript first appeared in Netscape 2.0 in 1995.
Audience and Prerequisites The tutorial is prepared for JavaScript beginners to help them understand the basic functionality for building dynamic web pages and web applications. It is assumed that the reader has prior knowledge of HTML coding. Some prior exposure to object-oriented programming concepts and a general idea of creating online applications would also be helpful.
Client-Side JavaScriptClient-side JavaScript is the most common form of the language. For the code to be interpreted by the browser, the script needs to be included in or referenced by an HTML document. This allows web pages to be dynamic, interacting with users, controlling the browser, and dynamically creating HTML content. Client-side JavaScript offers advantages over traditional server-side scripts, such as less server interaction, immediate feedback to visitors, increased interactivity, and richer interfaces.
Limitations of JavaScript Despite its capabilities, JavaScript is not considered a full-fledged programming language and has limitations. Client-side JavaScript does not allow reading or writing files for security reasons. It also lacks support for networking applications, multithreading, and multiprocessor capabilities. However, it excels at adding interactivity to static HTML pages.
JavaScript Development Tools A major advantage of JavaScript is that it does not require expensive development tools. You can start with a simple text editor like Notepad. As it’s an interpreted language within a web browser, a compiler is not needed. Several vendors offer more advanced JavaScript editing tools, such as Microsoft FrontPage, Macromedia Dreamweaver MX, and Macromedia HomeSite 5.
Where is JavaScript Today? Modern JavaScript implementations like Netscape’s JavaScript and Microsoft’s JScript conform to the ECMAScript standard.
Including JavaScript in HTML (Placement) JavaScript code is implemented using <script>…</script> HTML tags in a web page. These tags can be placed anywhere within the web page, but it is generally recommended to keep them within the <head> tags. The <script> tag signals the browser to interpret the text within it as a script. The <script> tag can have attributes like language (though its use is being phased out) and type, which should be set to “text/javascript”.
There are preferred ways to include JavaScript in an HTML file:
In the <head>…</head> section: This is often used for scripts that run on events, like user clicks.
In the <body>…</body> section: Scripts placed here typically run as the page loads to generate content.
In both <head> and <body> sections: You can have scripts in both sections.
In an external file: For reusing code across multiple pages, JavaScript can be stored in a .js file and included using the src attribute of the <script> tag in the <head> section.
Basic Syntax
Whitespace and Line Breaks: JavaScript ignores spaces, tabs, and newlines, allowing for flexible formatting to improve readability.
Semicolons: Semicolons at the end of simple statements are generally optional if each statement is on a separate line. However, it’s good programming practice to use semicolons.
Case Sensitivity: JavaScript is case-sensitive. Keywords, variables, function names, and identifiers must have consistent capitalization (e.g., Time and TIME are different).
Comments: JavaScript supports C-style (/* … */ for multi-line and single-line) and C++-style (// for single-line) comments. It also recognizes the HTML comment opening <!– as a single-line comment but requires the closing –> to be written as //–> to avoid being read as JavaScript code.
Enabling JavaScript in Browsers The tutorial outlines how to enable JavaScript in various browsers:
Internet Explorer: Through Tools -> Internet Options -> Security Tab -> Custom Level -> Scripting -> Active Scripting -> Enable.
Firefox: By typing about:config in the address bar, accepting the warning, searching for javascript.enabled, and toggling its value.
Chrome: Via Chrome menu -> Settings -> Show advanced settings -> Privacy -> Content settings -> Javascript and selecting the desired option.
Warning for Non-JavaScript Browsers The <noscript> tags can be used to display a warning message to users whose browsers do not support JavaScript or have it disabled. The content within <noscript> tags is displayed in place of the JavaScript code in such cases.
Variables JavaScript allows working with three primitive data types: Numbers, Strings, and Boolean. It also defines two trivial data types: null and undefined. Additionally, JavaScript supports a composite data type: object. Importantly, JavaScript does not distinguish between integer and floating-point numbers; all numbers are represented as 64-bit floating-point values according to the IEEE 754 standard.
Variables are named containers for storing data. They are declared using the var keyword. Multiple variables can be declared with a single var keyword. Variable initialization is the process of storing a value in a variable, which can happen at the time of declaration or later. The var keyword should only be used for the initial declaration or initialization of a variable. JavaScript is an untyped language, meaning a variable can hold a value of any data type, and the type can change during program execution.
Variable Scope JavaScript has two variable scopes:
Global Variables: Declared outside any function, they have global scope and can be accessed anywhere in the code.
Local Variables: Declared within a function, they are visible only within that function. Function parameters are always local. A local variable with the same name as a global variable takes precedence within the function, effectively hiding the global variable.
Variable Names When naming variables, the following rules apply:
Reserved JavaScript keywords cannot be used.
They should not start with a numeral (0-9) but must begin with a letter or an underscore.
They are case-sensitive.
Reserved Words The tutorial provides a list of reserved words that cannot be used as identifiers in JavaScript.
Operators JavaScript supports various types of operators:
Arithmetic Operators: These include + (addition, also for string concatenation), – (subtraction), * (multiplication), / (division), % (modulus), ++ (increment), and — (decrement).
Comparison Operators: These include == (equal), != (not equal), > (greater than), < (less than), >= (greater than or equal to), and <= (less than or equal to).
Logical Operators: These include && (logical AND), || (logical OR), and ! (logical NOT).
Bitwise Operators: These operate on the bit level and include & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (bitwise NOT), << (left shift), >> (right shift), and >>> (right shift with zero).
Assignment Operators: These assign values to variables and include = (simple assignment), += (add and assignment), -= (subtract and assignment), *= (multiply and assignment), /= (divide and assignment), and %= (modulus and assignment). Similar assignment operators exist for bitwise operations (e.g., <<=, >>=, &=, |=, ^=).
Miscellaneous Operators:Conditional Operator (? 🙂: This is a ternary operator that evaluates a condition and returns one of two expressions based on the result.
typeof Operator: This unary operator returns a string indicating the data type of its operand (e.g., “number”, “string”, “boolean”, “object”, “function”, “undefined”). Note that typeof null returns “object”.
This covers the fundamental aspects of JavaScript as introduced in the “JavaScript Basics” part of the tutorial. The subsequent parts delve into JavaScript Objects and Advanced topics.
JavaScript Language Features: Core Concepts
Based on the “javascript_tutorial.pdf” and our previous discussion, let’s delve into the language features of JavaScript:
Core Characteristics:
JavaScript is a lightweight, interpreted programming language. It is also described as a dynamic computer programming language.
It is designed for creating network-centric applications and is most commonly used as a part of web pages. Its implementations allow client-side script to interact with the user and make dynamic pages.
JavaScript has object-oriented capabilities.
It is complementary to and integrated with Java and HTML. In fact, it is considered very easy to implement because it is integrated with HTML.
JavaScript is open and cross-platform.
The core of the language has been embedded in various web browsers like Netscape and Internet Explorer.
The ECMA-262 Specification defined a standard version of the core JavaScript language, and JavaScript 2.0 conforms to Edition 5 of this standard.
Data Types:
JavaScript allows you to work with three primitive data types: Numbers, Strings of text, and Boolean (true or false).
It also defines two trivial data types: null and undefined, each having a single value.
JavaScript supports a composite data type known as object.
Notably, JavaScript does not distinguish between integer values and floating-point values. All numbers are represented as 64-bit floating-point format defined by the IEEE 754 standard.
Variables:
JavaScript uses variables as named containers to store data.
Variables are declared using the var keyword. Multiple variables can be declared with a single var keyword.
Variable initialization involves storing a value in a variable, which can occur during declaration or later.
JavaScript is an untyped language, meaning a variable can hold a value of any data type, and this type can change during the program’s execution.
Variables have scope: global scope (defined outside functions, accessible anywhere) and local scope (defined within a function, visible only there). Local variables take precedence over global variables with the same name within a function.
There are rules for naming variables: they cannot be reserved keywords, should not start with a numeral, must begin with a letter or underscore, and are case-sensitive.
Operators: JavaScript supports a variety of operators to perform operations on operands:
Arithmetic Operators: +, -, *, /, %, ++, –. The addition operator + can also be used for string concatenation.
Miscellaneous Operators:Conditional Operator (? 🙂: A ternary operator for conditional expressions.
typeof Operator: A unary operator that returns a string indicating the data type of an operand.
Syntax:
JavaScript code is typically placed within <script>…</script> tags in an HTML document.
These <script> tags can be located in the <head> or <body> sections of the HTML. JavaScript can also be included from external .js files using the src attribute of the <script> tag.
Whitespace (spaces, tabs, newlines) is generally ignored, allowing for code formatting to enhance readability.
Semicolons at the end of simple statements are optional if each statement is on a new line, but using them is considered good practice.
JavaScript is case-sensitive.
Comments can be added using // for single-line comments and /* … */ for multi-line comments. It also recognizes <!– as a single-line HTML comment, and //–> is used to close JavaScript within HTML comments for compatibility with older browsers.
These features collectively define the fundamental characteristics and capabilities of the JavaScript language as outlined in the initial sections of the provided tutorial.
JavaScript Core Concepts
Based on the “javascript_tutorial.pdf” and our conversation history, here’s a discussion of the core concepts of JavaScript:
What JavaScript Is: At its core, JavaScript is a lightweight, interpreted programming language. It’s also described as a dynamic computer programming language. Its primary design purpose is for creating network-centric applications, and it is most commonly used as a part of web pages. This allows for client-side scripting, enabling web pages to interact with the user and become dynamic. JavaScript is considered complementary to and integrated with both Java and HTML. Its integration with HTML makes it very easy to implement. Furthermore, it’s an open and cross-platform language. The general-purpose core of JavaScript has been embedded in various web browsers.
Client-Side Focus:Client-side JavaScript is the most prevalent form of the language. For JavaScript code to be interpreted and executed by the browser, it needs to be included in or referenced by an HTML document. This client-side mechanism provides significant advantages, such as less server interaction (by validating user input before submission) and immediate feedback to visitors (without requiring a page reload). It also enables increased interactivity and richer interfaces on web pages.
Basic Syntax: JavaScript code is typically placed within <script>…</script> HTML tags. These tags alert the browser to interpret the enclosed text as a script. The <script> tag can have attributes like language (though this is being phased out) and type, with the recommended type being “text/javascript”.
Key aspects of JavaScript syntax include:
Whitespace and Line Breaks: JavaScript generally ignores spaces, tabs, and newlines, allowing for flexible code formatting to improve readability.
Semicolons: While semicolons are optional if each statement is on a new line, it is considered good programming practice to use them. They are mandatory when multiple statements are on a single line.
Case Sensitivity: JavaScript is case-sensitive, meaning that keywords, variables, function names, and other identifiers must have consistent capitalization (e.g., Time and TIME are different).
Comments: JavaScript supports both C-style (/* … */ for multi-line and // for single-line) and recognizes the HTML comment opening (<!– as a single-line comment) and closing (//–>) sequences.
Variables and Data Types: JavaScript uses variables as named containers to store data. Before using a variable, it must be declared using the var keyword. Multiple variables can be declared with a single var. Initialization is the process of assigning a value to a variable, which can happen at declaration or later.
JavaScript is an untyped language, meaning a single variable can hold values of different data types during its lifetime. It supports several primitive data types:
Numbers: All numbers are treated as floating-point values using the 64-bit IEEE 754 standard.
Strings: Represent sequences of text (e.g., “Hello”).
Boolean: Represents logical values (true or false).
Null: A trivial type with only one value: null.
Undefined: Another trivial type with only one value: undefined.
In addition to these, JavaScript has a composite data type called object. Variables have scope, which can be global (accessible anywhere) or local (accessible only within a function).
Operators: JavaScript provides various operators to perform operations on values (operands):
Comparison Operators: Compare two operands and return a boolean value (== equal, != not equal, > greater than, < less than, >= greater than or equal to, <= less than or equal to).
Bitwise Operators: Operate on the binary representation of integers (& AND, | OR, ^ XOR, ~ NOT, << left shift, >> right shift, >>> unsigned right shift).
Assignment Operators: Assign values to variables (= simple assignment, += add and assign, -= subtract and assign, *= multiply and assign, /= divide and assign, %= modulus and assign, and similar for bitwise operators).
Miscellaneous Operators: Include the conditional (ternary) operator (? 🙂 for concise conditional expressions and the typeof operator to determine the data type of a variable.
Placement in HTML: JavaScript code can be included in an HTML document in several ways:
Directly within the <head>…</head> section, often used for scripts that run on events or utility functions.
Directly within the <body>…</body> section, typically for scripts that generate content as the page loads.
In both the <head> and <body> sections.
In an external .js file, which is then linked into the HTML using the src attribute of the <script> tag in the <head>. This promotes code reusability across multiple HTML pages.
Understanding these core concepts provides a foundational understanding of how JavaScript functions and its role in web development as described in the sources.
JavaScript’s Web Integration: Core Concepts
Based on the “javascript_tutorial.pdf” and our conversation history, JavaScript’s integration with the web is a fundamental aspect of its design and usage. Here’s a discussion of this web integration:
Core Role in Web Pages: JavaScript is most commonly used as a part of web pages. Its implementations allow client-side scripts to interact with the user and make dynamic pages. This is a primary reason for JavaScript’s existence and widespread adoption.
Client-Side Scripting: JavaScript is fundamentally a client-side scripting language. This means that the JavaScript code is typically embedded in or referenced by an HTML document and is then interpreted and executed by the user’s web browser. This client-side execution enables interactivity and dynamic content generation directly within the browser.
Complementary to and Integrated with HTML: The tutorial emphasizes that JavaScript is complementary to and integrated with HTML. In fact, it is considered very easy to implement because it is integrated with HTML. This close relationship means that JavaScript code works within the structure and content defined by HTML.
Inclusion in HTML using <script> Tags: JavaScript code is embedded within HTML documents using the <script>…</script> tags. These tags serve as containers for JavaScript code and instruct the browser to interpret the content between them as a script. The <script> tag can take attributes such as language (typically “javascript”, though being phased out) and type (recommended to be “text/javascript”).
Placement of <script> Tags: The tutorial details various ways to place <script> tags within an HTML document:
<head>…</head> Section: Placing scripts in the <head> section is often done for scripts that need to run on specific events or for utility functions that might be used throughout the page.
<body>…</body> Section: If a script needs to run as the page loads and generate content directly into the page, it is typically placed in the <body> section.
Both <head> and <body> Sections: It is possible to include JavaScript in both sections of an HTML document.
External File: For larger projects and reusability, JavaScript code can be stored in external files with the .js extension and then included in HTML files using the src attribute of the <script> tag, usually placed in the <head>. This allows for maintaining identical code across multiple pages.
Dynamic Content and User Interaction: By being integrated into web pages, JavaScript enables them to be dynamic. It can interact with the user, respond to their actions (like button clicks or mouse hovers), control the browser, and dynamically create HTML content. For example, JavaScript can be used to validate form input before submitting it to the server.
Event Handling: JavaScript can “trap user-initiated events” such as button clicks and link navigation, allowing developers to execute specific code in response to these interactions. The tutorial later introduces the concept of “Events” and specific event types like onclick, onsubmit, and onmouseover/onmouseout, further illustrating this interaction.
Basic Output and DOM Manipulation (Implicit): While the Document Object Model (DOM) is formally introduced later in the tutorial, the early examples using document.write() demonstrate a basic level of interaction with the HTML document to output content. This is a fundamental aspect of JavaScript’s web integration – its ability to manipulate the structure and content of the web page.
Handling Browsers Without JavaScript: Recognizing that some browsers might not support JavaScript or have it disabled, the tutorial mentions the <noscript> tags. Content within these tags is displayed to users if their browser does not support JavaScript or if JavaScript is not enabled, allowing for a fallback mechanism or a warning message.
In summary, JavaScript’s web integration is characterized by its role as a client-side scripting language deeply intertwined with HTML, enabling dynamic behavior, user interaction, and content manipulation within web browsers. The <script> tag and its various placement options are key mechanisms for incorporating JavaScript into web pages, with external files promoting code organization and reusability.
JavaScript Development Tools: Simplicity and Enhanced Editors
Based on the “javascript_tutorial.pdf”, here’s a discussion of JavaScript development tools:
The tutorial points out that one of the significant advantages of JavaScript is that it does not require expensive development tools. You can begin writing JavaScript code with a simple text editor such as Notepad. Since JavaScript is an interpreted language within the context of a web browser, you don’t even need to buy a compiler.
However, the tutorial also mentions that various vendors have created nice JavaScript editing tools to make development simpler. Some of these tools listed in the source are:
Microsoft FrontPage: Described as a popular HTML editor that also provides web developers with JavaScript tools to assist in creating interactive websites.
Macromedia Dreamweaver MX: Identified as a very popular HTML and JavaScript editor among professional web developers. It offers prebuilt JavaScript components, integrates well with databases, and conforms to new standards like XHTML and XML.
Macromedia HomeSite 5: Presented as a well-liked HTML and JavaScript editor from Macromedia, suitable for effectively managing personal websites.
In summary, the tutorial highlights that basic JavaScript development can start with a simple text editor and a web browser. For more enhanced development experiences, dedicated HTML and JavaScript editors like Microsoft FrontPage, Macromedia Dreamweaver MX, and Macromedia HomeSite 5 are available, offering features that can simplify the process of building interactive websites. Our previous conversations have focused on the core concepts and web integration of JavaScript and did not delve into specific development tools beyond what is mentioned in this source.
Affiliate Disclosure: This blog may contain affiliate links, which means I may earn a small commission if you click on the link and make a purchase. This comes at no additional cost to you. I only recommend products or services that I believe will add value to my readers. Your support helps keep this blog running and allows me to continue providing you with quality content. Thank you for your support!
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
What are the three core technologies of the web?
Explain the difference between interpreted and compiled code.
Briefly describe the Document Object Model (DOM).
What is an asynchronous request, and why is it useful in web development?
What is the purpose of the parseFloat() function? How does it differ from parseInt()?
Explain the concept of “truthy” and “falsy” values in JavaScript, and give one example of each.
What does NaN represent in JavaScript, and list two operations that result in NaN.
Describe what the modulus operator (%) does.
Explain the difference between == and === comparison operators in JavaScript.
What is type coercion in JavaScript, and how does it differ from type conversion?
Quiz Answer Key
HTML, CSS, and JavaScript. HTML structures web content, CSS styles the content, and JavaScript brings interactivity to the front-end.
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.
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.
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.
The parseFloat() function converts a string to a floating-point number. parseInt() converts a string to an integer, discarding any decimal portion.
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, “”).
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.
The modulus operator (%) returns the remainder of a division operation. For example, 7 % 5 equals 2.
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.
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
Discuss the versatility of JavaScript and the reasons for its popularity in modern web development.
Explain the differences between client-side and server-side JavaScript. Give examples of frameworks or environments associated with each.
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.
Explain the execution context in JavaScript, including the memory creation phase and execution phase. How does the execution context differ when invoking a function?
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:
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”
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.
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.
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.
“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”
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.
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.
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”
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.
Arrays and Objects
Section introduction: Will cover creating, manipulating and nesting arrays and objects.
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.
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.
Logic and Control Flow
IF statements
IF ELSE statements
Truthy and Falsy values
Logical Operators
SWITCH statements
TERNARY Operator
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:
* **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).
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.
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.
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
Affiliate Disclosure: This blog may contain affiliate links, which means I may earn a small commission if you click on the link and make a purchase. This comes at no additional cost to you. I only recommend products or services that I believe will add value to my readers. Your support helps keep this blog running and allows me to continue providing you with quality content. Thank you for your support!
This YouTube transcript presents a comprehensive JavaScript course designed for beginners. The course covers fundamental concepts such as variables, data types, operators, control flow, functions, objects, classes, and the Document Object Model (DOM). It emphasizes practical application through real-world projects like a notes app, quiz app, and e-commerce product page. The transcript also includes explanations of JavaScript scope, event handling, and advanced topics like constructor functions and prototypes. Finally, there are instructions for building applications like a digital clock and a form validation project.
JavaScript Fundamentals Study Guide
Quiz
Instructions: Answer the following questions in 2-3 sentences each.
What is JavaScript, and what are two common uses for it in web development?
Describe three different ways you can embed JavaScript code in an HTML file.
Explain the difference between the var, let, and const keywords when declaring variables in JavaScript.
Define “scope” in JavaScript, and name the three types of scope.
Name four of the seven primitive data types in JavaScript and give an example of each.
Explain the difference between the == and === operators in JavaScript.
Describe the purpose of control flow statements in JavaScript and give one example of a conditional statement.
Explain the difference between the break and continue statements within a JavaScript loop.
What is a JavaScript function, and how is it defined and called?
What is a JavaScript object, and how do you access properties and methods within it?
Quiz Answer Key
JavaScript is a scripting language used to create interactive and dynamic websites. It’s commonly used for front-end web development to add interactivity, such as button clicks and form validation, and also used in back-end web development with Node.js.
JavaScript code can be embedded in an HTML file in the <head> tag within <script> tags, within the <body> tag, or through an external JavaScript file linked using the src attribute in the <script> tag.
var is the oldest and most common way to declare variables, with function scope. let is a newer keyword that declares block-scoped variables, meaning they are only visible within the block in which they are declared. const is used to declare constants, which are variables that cannot be reassigned once they are declared.
Scope refers to the visibility of variables and functions within a program. There are three types of scope in JavaScript: global scope, function scope, and block scope.
Four primitive data types in JavaScript are: string (e.g., “Hello World”), number (e.g., 3.14), boolean (e.g., true), and undefined (a variable that has been declared but not assigned a value).
The == operator checks for equality of values after type coercion, meaning it may convert the types of the operands before comparison. The === operator checks for strict equality, meaning it compares both the value and the type of the operands without type coercion.
Control flow statements are used to control the order in which code is executed in a JavaScript program. An example of a conditional statement is the if statement, which executes a block of code only if a specified condition is true.
The break statement is used to terminate a loop immediately, while the continue statement skips the current iteration of the loop and proceeds to the next iteration.
A JavaScript function is a reusable block of code that performs a specific task. It’s defined using the function keyword followed by the function name, parameters (optional), and the code block enclosed in curly braces. It’s called by using the function name followed by parentheses.
A JavaScript object is a non-primitive data type that stores a collection of data in key-value pairs. You can access properties using dot notation (e.g., object.property) or bracket notation (e.g., object[“property”]). Methods are functions associated with the object and are accessed the same way as properties (e.g. object.method()).
Essay Questions
Discuss the importance of understanding variable scope in JavaScript and how different types of scope can affect the behavior of your code. Provide examples to illustrate your points.
Explain the concept of data types in JavaScript, differentiating between primitive and reference data types. How does an understanding of data types contribute to writing robust and error-free code?
Describe the various operators available in JavaScript, categorizing them by function (arithmetic, assignment, comparison, logical). Explain how operator precedence and associativity impact the evaluation of expressions.
Compare and contrast the different looping structures available in JavaScript (for, while, do…while). Provide scenarios where each type of loop would be most appropriate and justify your choices.
Explain the concept of DOM (Document Object Model). Discuss DOM manipulation techniques using JavaScript. What is the importance of DOM manipulation in web development?
Glossary of Key Terms
JavaScript: A scripting language primarily used to create interactive and dynamic websites.
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.
Variable: A storage location that holds a value.
Keyword: A reserved word that has a special meaning in the JavaScript language.
Scope: The visibility of variables and functions in a JavaScript program.
Global Scope: Variables declared outside any function or block, accessible from anywhere in the script.
Function Scope: Variables declared inside a function, only accessible within that function.
Block Scope: Variables declared inside a block (e.g., within an if statement or loop), only accessible within that block (introduced with let and const).
Data Type: The type of value that a variable can hold (e.g., string, number, boolean).
Primitive Data Type: Basic data types that represent a single value (string, number, boolean, null, undefined, symbol, bigInt).
String: A sequence of characters enclosed in single or double quotes.
Number: Represents numeric values, including integers and floating-point numbers.
Boolean: A data type with two possible values: true or false.
Undefined: A value assigned to a variable that has been declared but not yet assigned a value.
Operator: A symbol that performs an operation on one or more operands.
Arithmetic Operators: Operators used to perform mathematical calculations (e.g., +, -, *, /).
Assignment Operators: Operators used to assign values to variables (e.g., =, +=, -=).
Comparison Operators: Operators used to compare two values (e.g., ==, ===, >, <).
Logical Operators: Operators used to perform logical operations (e.g., &&, ||, !).
Operator Precedence: The order in which operators are evaluated in an expression.
Operator Associativity: The direction in which operators of the same precedence are evaluated (left-to-right or right-to-left).
Control Flow Statements: Statements that control the order in which code is executed (e.g., if, else, switch, for, while).
Conditional Statement: A statement that executes different code based on a condition (e.g., if, else if, else).
Loop: A control flow statement that repeats a block of code multiple times (e.g., for, while, do…while).
Function: A reusable block of code that performs a specific task.
Parameter: A variable declared in a function definition that receives a value when the function is called.
Argument: The actual value passed to a function when it is called.
Return Statement: A statement that ends the execution of a function and returns a value (optional).
Object: A collection of properties (key-value pairs).
Property: A key-value pair in an object, where the key is a string (or symbol) and the value can be any data type.
Method: A function that is a property of an object.
this Keyword: A keyword that refers to the current object in a method.
Constructor Function: A function used to create objects.
new Keyword: An operator used to create an instance of an object from a constructor function.
class Keyword: A keyword used to define a class, which is a blueprint for creating objects (introduced in ES6).
Getter: A special method in JavaScript that is called when a property is accessed, used to retrieve property values.
Setter: A special method in JavaScript that is called when a property is modified, used to set property values.
Event: An action that occurs in the web browser, such as a click, mouseover, or keypress.
Event Listener: A function that is executed when a specific event occurs.
Element: An individual component of an HTML document.
Node: A generic term for any type of object in the DOM tree (e.g., element, text, comment).
Parent Node: The node directly above another node in the DOM tree.
Child Node: A node directly below another node in the DOM tree.
Sibling Node: Nodes that share the same parent node in the DOM tree.
document.getElementById(): A DOM method to select a specific element.
document.querySelector(): A DOM method to select an element using CSS selectors.
document.querySelectorAll(): A DOM method to select a set of elements using CSS selectors.
element.parentNode: Returns parent element of specified node.
element.children: Returns HTMLCollection of an element’s child elements.
element.innerHTML: Sets or returns the content of an element.
element.textContent: Sets or returns the text content of an element.
element.setAttribute(): Sets the value of an attribute on the specified element.
element.classList: Returns the class names of an element.
Event Bubbling: Is an event flow model in which event flows from the most specific element to the least specific.
Event Capturing: Is an event flow model in which event flows from the least specific element to the most specific.
JavaScript Tutorial: A Beginner’s Guide
Okay, here’s a detailed briefing document summarizing the main themes and important ideas from the provided JavaScript tutorial excerpts.
Briefing Document: JavaScript Tutorial Overview
I. Main Themes
Introduction to JavaScript: The core of the excerpts focuses on introducing JavaScript as a scripting language essential for creating interactive and dynamic websites. It emphasizes its widespread use and relevance in modern web development.
Beginner-Friendly Approach: The tutorial is explicitly designed for individuals with no prior coding experience. It promises clear explanations, practical examples, and complete notes to facilitate learning.
Practical Application and Projects: A key element is the emphasis on learning by doing. The tutorial promises real-world projects (online notes app, quiz app, etc.) to solidify understanding.
Fundamental Concepts: The tutorial covers essential JavaScript concepts, including variables, data types, operators, control flow statements, functions, objects, and DOM manipulation.
Modern JavaScript Features: The excerpts touch on newer JavaScript features introduced in ES6, such as the let keyword and default parameters.
Emphasis on DOM (Document Object Model): A significant portion is dedicated to understanding and manipulating the DOM, enabling dynamic interaction with web page elements.
Event Handling: An introduction to JavaScript events, detailing how to make web pages interactive.
Project-Based Learning: Several mini-projects are outlined to provide hands-on experience in applying JavaScript concepts.
II. Important Ideas and Facts
What is JavaScript?“JavaScript is a scripting language that is used to create interactive and dynamic websites.”
Interactive websites: enable user actions like “button click, submit a form, write comments, and live chat.”
Dynamic websites: change content/layout like “sliding effect, e-commerce website and quiz website.”
Why Learn JavaScript?“JavaScript is the most popular programming language in the world.”
Used by major websites: “Google, Facebook, Twitter, Amazon, Netflix.”
Vast ecosystem: “tons of Frameworks and libraries to reduce your time to create websites and mobile apps some of the popular Frameworks are react angular and vuejs.”
Career opportunities: “if you learn JavaScript it opens a lot of job opportunities in the software development Industries.”
Uses of JavaScript:Beyond front-end: “not only limited to front-end web development it is also used in backend web development mobile app development desktop app development game development and API creation.”
Setting Up a Development Environment:Requires a web browser (e.g., Google Chrome) and a code editor (e.g., Visual Studio Code).
Adding JavaScript to HTML:Inline: Within <script> tags in the <head> or <body>.
External: Using <script src=”script.js”></script>, linking to an external .js file.
“There are multiple options to display the output of JavaScript on the web page or browser.”
alert(“message”): Displays an alert box.
document.write(“message”): Writes directly to the HTML document.
console.log(“message”): Logs messages to the browser’s console.
Variables:“Variables are used to store data.”
Declaration: var, let, const.
var: Oldest, most common way.
let: Block-scoped (ES6).
const: Declares constants (cannot be reassigned).
Naming: Must begin with “alphabet dollar sign or underscore”.
Case-sensitive: “JavaScript is case sensitive”.
Scope:Global: Accessible from anywhere.
“variables and functions declared in the global scope are visible from anywhere in the program”
Function: Only accessible within the function.
“variables and functions declared in a functions scope are only ual within that function”
Block: Only accessible within the block (e.g., within an if statement).
“variables and functions declared in a block scope are only visible within that block”
Data Types:Primitive: String, Number, Boolean, Null, Undefined, BigInt, Symbol.
String: “a string is a sequence of zero or more characters”
Number: represents integer and floating point numbers
Boolean: true or false values
Reference: Object, Array, Function.
Object: “a non-primitive data type that allows you to store multiple collections of data”
Array: “arrays are a type of object that stores a collection of values”
Function: “functions are a type of object that can be used to execute code”
Dynamic Typing: “JavaScript is a dynamically typed language so we can store different data type in the same variable.”
Accessing properties: objectName.propertyName or objectName[“propertyName”].
Methods: Functions within objects.
this keyword: Refers to the current object.
Getters and Setters: Special methods to control property access and modification.
Classes:A blueprint for creating objects.
constructor: A special method to initialize object properties.
Methods: Functions within classes.
Inheritance: Creating new classes based on existing ones (using extends).
Private methods: A method inside of the class that can not be accessed from outside the class.
Static methods: can be accessed without creating an object of the class
DOM (Document Object Model):Represents the structure of an HTML document as a tree.
Nodes: Elements, text, attributes, etc.
Traversing: Moving through the DOM tree (parent, children, siblings).
parentNode: Returns the parent element of a node.
firstChild, lastChild: First and last child nodes.
childNodes: All child nodes.
nextElementSibling, previousElementSibling: Next and previous sibling elements.
Selecting Elements:
document.getElementById(“id”): Selects an element by its ID.
document.getElementsByClassName(“class”): Selects elements by class name (returns an HTMLCollection).
document.getElementsByTagName(“tag”): Selects elements by tag name (returns an HTMLCollection).
document.querySelector(“selector”): Selects the first element matching a CSS selector.
document.querySelectorAll(“selector”): Selects all elements matching a CSS selector (returns a NodeList).
Manipulating Elements:
document.createElement(“tag”): Creates a new HTML element.
element.appendChild(newNode): Adds a node as a child to an element.
element.textContent = “text”: Sets the text content of an element.
element.innerHTML = “html”: Sets the HTML content of an element.
element.setAttribute(“attribute”, “value”): Sets the value of an attribute.
element.removeAttribute(“attribute”): Removes an attribute.
element.classList: For adding, removing, and toggling CSS classes.
Adding and Removing elements:
element.insertAdjacentHTML(): A method to add HTML adjacent to an element.
replaceChild(): replaces a child element with a new one.
cloneNode(): clones a node.
removeChild(): removes a child element of a node.
insertBefore(): insert a new node before an existing node.
Attributes:
“The ID is the attribute name username is the attribute value”
to get the attributes of any HTML element use javaScript.
hasAttribute(): used to check whether an element has a specified attribute or not.
getAttribute(): method use to get the value of specified attribute.
setAttribute(): set the attribute.
removeAttribute(): remove the attribute.
Events:Actions that occur in the browser (e.g., click, mouseover, load).
Event bubbling: Event flow from the most specific element to the least.
Event capturing: Starts from the least specific element.
III. Examples of Projects Mentioned
Online Notes App
Quiz App
Form Validation
Image Slider
Digital Clock
E-commerce Product Page
To-Do List App
Weather App
Calculator
Image Gallery
IV. Conclusion
The provided excerpts outline a comprehensive JavaScript tutorial suitable for beginners. It covers fundamental concepts, practical application through projects, and introduces modern JavaScript features. The emphasis on DOM manipulation and event handling highlights the tutorial’s focus on building interactive web experiences. By following this course, individuals with no prior programming experience can become proficient in JavaScript and be able to develop real-world applications.
JavaScript FAQs: A Quick Reference
Frequently Asked Questions about JavaScript
1. What is JavaScript and what are its primary uses?
JavaScript is a scripting language primarily used to create interactive and dynamic websites. It enables user actions like button clicks, form submissions, live chats, and website content or layout changes such as sliding effects, e-commerce functionalities, and quizzes. It can be used in front-end web development, back-end web development, mobile app development, desktop app development, game development, and API creation.
2. Why should I learn JavaScript?
JavaScript is the most popular programming language globally, used by almost all popular websites like Google, Facebook, Twitter, Amazon, and Netflix. It has numerous frameworks and libraries like React, Angular, and Vue.js, which help reduce development time. Learning JavaScript opens many job opportunities in the software development industry.
3. How can I get started with writing JavaScript code?
To start writing JavaScript, you need a web browser (like Google Chrome) and a code editor (like Visual Studio Code). You can add JavaScript code directly within the HTML file using the <script> tag in the <head> or <body>, or you can link an external JavaScript file using <script src=”script.js”></script>.
4. What are variables in JavaScript and how do I declare them?
Variables are used to store data. In JavaScript, you declare variables using the var, let, or const keywords. For example: var x = 30;, let x = 10;, or const a = 4;. var is the oldest and most common way, let is a newer keyword introduced in ES6 for block-scoped variables, and const is used for variables that should not be reassigned. Variable names must begin with an alphabet, dollar sign ($), or underscore (_).
5. What is scope in JavaScript and what are the different types?
Scope refers to the visibility of variables and functions within a program. There are three types of scope in JavaScript:
Global scope: Variables and functions declared in the global scope are visible from anywhere in the program.
Function scope: Variables and functions declared within a function are only visible within that function.
Block scope: Variables and functions declared within a block of code (enclosed in curly braces) are only visible within that block (using let or const).
6. What are the different data types in JavaScript?
JavaScript has two main categories of data types:
Primitive data types: These include string, number, boolean, null, undefined, bigint, and symbol.
Reference data types: These include object, array, and function.
JavaScript is a dynamically typed language, allowing you to store different data types in the same variable during its lifecycle.
7. What are operators in JavaScript and what are some common types?
Operators are symbols used to perform operations on operands (values and variables). Common types include:
Arithmetic operators: Used for mathematical operations (e.g., +, -, *, /, %).
Assignment operators: Used to assign values to variables (e.g., =, +=, -=).
Comparison operators: Used to compare two values (e.g., ==, ===, !=, >, <). They return Boolean values.
Logical operators: Used to perform logical operations (e.g., && (AND), || (OR), ! (NOT)).
String operators: Used to concatenate strings (e.g., +).
8. What are control flow statements in JavaScript and how are they used?
Control flow statements are used to control the flow of execution in a JavaScript program. There are three main types:
Conditional statements: (e.g., if, else if, else, switch) used to execute different code based on different conditions.
Loops: (e.g., for, while, do…while) used to repeat a block of code.
try…catch statements: Used to handle errors.
9. What are functions in JavaScript and how are they used?
Functions are reusable blocks of code that perform specific tasks. You can define a function using the function keyword, followed by the function name, parameters (optional), and the function body. Functions can return values using the return statement. Parameters act as placeholders that receive argument values passed during the function call.
10. How do parameters and arguments work in Javascript functions?
Parameters are declared in the function definition, while arguments are the actual values passed to the function when it’s called. You can also use default parameters, which provide a default value if an argument is not provided when calling the function. JavaScript functions can be declared without names, also known as anonymous functions and can call upon themselves, known as recursion.
11. What are objects in JavaScript and how do I work with them?
Objects are non-primitive data types that store collections of data in key-value pairs. You can create objects using curly braces {}. Access properties using dot notation (e.g., object.property) or bracket notation (e.g., object[‘property’]). You can add, modify, and delete properties of an object. Objects can contain other objects, which are called nested objects, and methods.
12. How do I define and use methods within JavaScript objects?
Methods are functions that are properties of an object. You can define methods within an object using function expressions or by directly assigning a function to a property. You can call object methods using dot notation followed by parentheses (e.g., object.method()). To access other properties of the object within a method, you can use the this keyword.
13. What is the DOM (Document Object Model) and how do I use it to manipulate web pages?
The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. It allows JavaScript to dynamically access and update the content, structure, and style of web pages. You can select elements using methods like getElementById, getElementsByClassName, getElementsByTagName, querySelector, and querySelectorAll. You can traverse the DOM to navigate between parent, child, and sibling elements. You can manipulate elements by creating new elements, appending or inserting them, modifying content and attributes, and removing elements.
14. How do I handle events in JavaScript?
Events are actions that occur in the web browser (e.g., clicks, mouse movements, page loads). You can handle events using event listeners, which are functions that are executed when a specific event occurs. The two event models are event bubbling (event flows from the most specific element to the least) and event capturing (event flows from the least specific element to the most).
15. What are classes in JavaScript and how do I use them?
Classes are a template for creating objects. They are a way to organize and structure your code using object-oriented programming principles. A constructor is a special method within a class that is called when a new object is created from the class. The new keyword is used to create an instance of a class. Getters and setters are special methods that allow you to control how properties are accessed and modified. Using the # prefix indicates that the method is private. Static methods and properties are associated with the class itself, rather than with individual instances of the class. This means that you can access them directly using the class name without having to create an object.
JavaScript Fundamentals: Variables, Data Types, and DOM Manipulation
JavaScript is a scripting language utilized to create dynamic and interactive websites. A dynamic website can alter its content and layout, while an interactive website enables user actions like button clicks or form submissions.
Key aspects of JavaScript covered in the sources include:
Variables and Scope Variables are used to store data and are declared using keywords like var, let, and const. The let keyword declares block-scoped variables, visible only within their defined block, while const declares variables that cannot be reassigned. JavaScript recognizes three types of scope: global, function, and block scope.
Data Types JavaScript divides data types into primitive and reference types. Primitive data types include string, number, boolean, null, undefined, bigint, and symbol. Reference data types include object, array, and function. JavaScript is a dynamically typed language, allowing variables to store different data types.
Operators Operators are symbols that perform operations on operands (values and variables). Types include arithmetic, assignment, comparison, logical, and string operators. Operator precedence determines the order in which operators are processed.
Control Flow Statements These statements manage the execution flow in a JavaScript program, enabling decisions, loops, and error handling. Common conditional statements are if, else if, and else. Loops include for, while, and do while loops. The break statement exits a loop, and the continue statement skips the current iteration.
Functions Functions are reusable code blocks that perform specific tasks. They are defined using the function keyword and can accept parameters and return values. Functions can be recursive, calling themselves within their own code. A callback is a function passed as an argument to another function.
Objects Objects store collections of data in key-value pairs. Objects can contain properties (data) and methods (functions). The this keyword refers to the object in which it is used. A constructor function is used to create objects.
Prototypes Every JavaScript object has a prototype property. Prototypes allow objects to inherit properties and methods.
Classes Introduced in ES6, classes are templates for creating objects. They contain a constructor method for initializing object properties and can have other methods.
DOM (Document Object Model) The DOM represents HTML documents, allowing JavaScript to manipulate webpage content and structure. Methods like getElementById, getElementsByName, getElementsByTagName, querySelector, and querySelectorAll are used to select HTML elements. JavaScript can modify element attributes, styles, and classes using DOM manipulation techniques.
Events Events are actions that occur in a web browser, like clicks or mouse movements. Event listeners are used to execute code in response to specific events. Common events include mousemove, mousedown, mouseup, mouseover, mouseout, keydown, keyup, and scroll.
JavaScript DOM Manipulation Essentials
DOM (Document Object Model) is an API for manipulating HTML documents. The DOM represents an HTML document as a tree of nodes, where each HTML tag, attribute, or text is a node.
Selecting Elements To access and manipulate elements within an HTML document, JavaScript provides several DOM methods:
getElementById(id): Retrieves the element with the specified id attribute.
getElementsByName(name): Returns a collection of elements with the given name attribute.
getElementsByTagName(tagname): Returns a collection of elements with the specified tag name.
getElementsByClassName(classname): Returns a collection of elements with the given class name.
querySelector(selector): Returns the first element that matches the specified CSS selector.
querySelectorAll(selector): Returns a collection of all elements that match the specified CSS selector.
Traversing Elements Once an element is selected, you can navigate the DOM tree to access its related nodes:
parentNode: Gets the parent node of the specified node.
firstChild: Gets the first child node of the specified element.
lastChild: Gets the last child node of the specified element.
childNodes: Gets all child nodes of the specified element.
firstElementChild: Gets the first element child of the specified element.
lastElementChild: Gets the last element child of the specified element.
nextElementSibling: Gets the next sibling element of the specified element.
previousElementSibling: Gets the previous sibling element of the specified element.
Modifying Elements JavaScript provides several ways to modify HTML elements:
createElement(tagname): Creates a new HTML element with the specified tag name.
appendChild(node): Adds a node to the end of the list of child nodes for a specified parent node.
textContent: Gets or sets the text content of a node and its descendants.
innerHTML: Gets or sets the HTML code within an element.
after(node or string): Inserts one or more nodes or strings after the element.
append(node or string): Appends new nodes or strings to the end of the children of an element.
prepend(node): Adds a new node as the first child of an element.
insertAdjacentHTML(position, text): Inserts HTML code at a specified position relative to the element.
replaceChild(newchild, oldchild): Replaces a child element with a new one.
cloneNode(deep): Clones an element, optionally including its descendants (deep is a boolean value).
removeChild(child): Removes a child element from a node.
insertBefore(newnode, existingnode): Inserts a new node before an existing node as a child of a parent node.
Attribute Manipulation HTML attributes can be accessed and modified using the following methods:
attributes: Returns a collection of all attributes of an element.
getAttribute(name): Gets the value of the attribute with the specified name.
setAttribute(name, value): Sets the value of an attribute.
hasAttribute(name): Returns a boolean value indicating whether the element has the specified attribute.
removeAttribute(name): Removes the attribute with the specified name.
Style Manipulation The style of an element can be manipulated using the style property:
element.style.property: Gets or sets the value of an inline style property.
Class Manipulation CSS classes of an element can be manipulated using the following properties:
className: Gets or sets the class name of an element as a string.
classList: Returns a collection of CSS classes of an element, providing methods to add, remove, toggle, and check classes.
add(classname): Adds a CSS class to the element.
remove(classname): Removes a CSS class from the element.
replace(oldclass, newclass): Replaces an existing class with a new one.
contains(classname): Checks if the element contains a specific class.
toggle(classname): Adds the class if it doesn’t exist or removes it if it does.
Events Events are actions that occur in a web browser. Event listeners are used to execute code in response to specific events. There are three ways to assign event handlers:
Using HTML attributes.
Assigning event handler names in JavaScript.
Using the addEventListener method.
The addEventListener method accepts three arguments: the event type, the function to be executed when the event fires, and an optional boolean value indicating whether to use capture. The removeEventListener method removes an event listener that was added using addEventListener.
JavaScript Events and Event Handlers
Events are actions that occur in a web browser, like clicks or mouse movements. An event handler, also known as an event listener, is a piece of code that will be executed when the event occurs.
There are three ways to assign event handlers:
Using HTML attributes: For each event, there is an event handler, and their names typically begin with on. For example, the event handler for a click event is onclick. The JavaScript code can be added within the quotes of the HTML attribute. The event handler attribute can also call a function. When the event occurs, the web browser passes an event object to the event handler. Inside the event handler, the this keyword refers to the target element on which the event occurs.
Assigning event handler names in JavaScript: The event handler can be added to the HTML element in the JavaScript code. For example, element.onclick = function(){}. In this method also, the this keyword refers to the target element. To remove the event handler, assign null to the event handler.
Using the addEventListener method: The addEventListener method registers an event handler, and the removeEventListener method removes an event handler that was added using addEventListener. The addEventListener accepts three arguments: the event type, the function to be executed when the event fires, and an optional boolean value indicating whether to use capture.
Some useful JavaScript events:
mousemove: Fires repeatedly when you move the mouse cursor around the element.
mousedown: Fires when you press the mouse button on the element.
mouseup: Fires when you release the mouse button on the element.
mouseover: Occurs when the mouse cursor moves from outside to inside the boundaries of the element.
mouseout: Occurs when the mouse cursor is over an element and then moves to another element.
keydown: Fires when you press a key on the keyboard and fires repeatedly while you are holding down the key.
keyup: Fires when you release a key on the keyboard.
keypress: Occurs when you press a character keyboard like ABC and fires repeatedly while you hold down the key on the keyboard.
scroll: Occurs when you scroll a document or an element.
When an event occurs, the event flows from the most specific element to the least specific element; this is event bubbling. When the event starts at the least specific element and flows towards the most specific element, this event model is known as event capturing.
JavaScript Prototypes: Inheritance, Properties, and Methods
In JavaScript, every function and object has its own property called prototype. A prototype itself is also an object, creating a prototype chain.
Key aspects of JavaScript prototypes include:
Prototype Inheritance You can use the prototype to add properties and methods to a Constructor function, and objects inherit the properties and methods from a prototype.
Adding Properties To add a new property to a constructor function, use function name.prototype.property name = value.
Adding Methods To add a method, use function name.prototype.method name = function(){}.
Accessing Properties and Methods Objects created with the constructor function can access the properties and methods defined in the prototype.
Changing Prototype Values If a prototype value is changed, all new objects will have the changed property value, while previously created objects will have the previous value.
For example, consider a constructor function Person:
function Person(first, last) {
this.firstName = first;
this.lastName = last;
}
To add a new property called gender to the Person constructor function, use the prototype:
Person.prototype.gender = “male”;
To add a method called getFullName, use the prototype as well:
Person.prototype.getFullName = function() {
return this.firstName + ” ” + this.lastName;
}
Now, create two objects using the Person constructor function:
const person1 = new Person(“Elon”, “Musk”);
const person2 = new Person(“Bill”, “Gates”);
The objects person1 and person2 can access the gender property and getFullName method:
console.log(person1.gender); // Output: male
console.log(person2.getFullName()); // Output: Bill Gates
JavaScript and the DOM: Manipulating HTML Elements
The sources provide information on manipulating HTML elements using JavaScript, primarily through the DOM (Document Object Model).
Selecting HTML Elements To begin manipulating HTML elements, they must first be selected. Several DOM methods are available for this purpose:
getElementById(id): Selects an element by its id attribute.
getElementsByName(name): Retrieves all elements with a specific name attribute.
getElementsByTagName(tagname): Selects all elements with a given tag name.
getElementsByClassName(classname): Selects all elements with a specified class name.
querySelector(selector): Selects the first element that matches a CSS selector.
querySelectorAll(selector): Selects all elements that match a CSS selector.
Traversing HTML Elements After selecting an element, it’s possible to navigate the DOM tree to reach related elements:
parentNode: Accesses the parent node of an element.
firstChild: Accesses the first child node of an element.
lastChild: Accesses the last child node of an element.
childNodes: Provides a collection of all child nodes of an element.
firstElementChild: Accesses the first element child of an element.
lastElementChild: Accesses the last element child of an element.
nextElementSibling: Accesses the next sibling element of an element.
previousElementSibling: Accesses the previous sibling element of an element.
Modifying HTML Elements JavaScript offers various methods for modifying HTML elements:
createElement(tagname): Creates a new HTML element with the specified tag name.
appendChild(node): Adds a node as the last child of a parent node.
textContent: Sets or retrieves the text content of an element, ignoring HTML tags.
innerHTML: Sets or retrieves the HTML content within an element, interpreting HTML tags.
after(node or string): Inserts a node or string after a specified element.
append(node or string): Appends a node or string to the end of an element’s children.
prepend(node): Adds a node as the first child of an element.
insertAdjacentHTML(position, text): Inserts HTML at a specified position relative to an element.
replaceChild(newchild, oldchild): Replaces one child element of a node with another.
cloneNode(deep): Clones an HTML element. The deep argument specifies whether to clone all descendant nodes as well.
removeChild(child): Removes a child element from a node.
insertBefore(newnode, existingnode): Inserts a new node before an existing node.
Working with HTML Attributes Attributes of HTML elements can be accessed and changed with these methods:
attributes: Returns a collection of all attributes of an element.
getAttribute(name): Retrieves the value of the attribute with the specified name.
setAttribute(name, value): Sets the value of an attribute.
hasAttribute(name): Checks if an element has a specific attribute.
removeAttribute(name): Removes an attribute from an element.
Manipulating Element Style The style property is used to manipulate the inline styles of an HTML element:
element.style.property: Retrieves or sets the value of a CSS property.
element.style.cssText: Sets multiple CSS properties at once. Using += with cssText allows appending new styles without overriding existing ones.
getComputedStyle(element): Returns an object containing the values of all CSS properties of an element, including those from external stylesheets.
Manipulating Classes CSS classes can be manipulated for styling purposes:
className: Gets or sets the class name of an element. Assigning a new value overwrites existing classes, but concatenation can be used to add classes without removing existing ones.
classList: Provides methods for adding, removing, and toggling CSS classes.
add(classname): Adds a class to an element.
remove(classname): Removes a class from an element.
replace(oldclass, newclass): Replaces one class with another.
contains(classname): Checks if an element has a specific class.
toggle(classname): Adds or removes a class, depending on its presence.
JavaScript Full Course For Beginners With JavaScript Projects Tutorial And Notes 2024
The Original Text
hi guys welcome back to another video of greatest tack if you think JavaScript is difficult to learn and tired of watching multiple tutorials of JavaScript and still not feeling confident well you have come to the right video by the way this is not just a simple video but it is an ultimate course to start your journey into the exciting world of JavaScript in this JavaScript course we will start from the absolute Basics and I will guide you through the fundamentals of JavaScript that will help you to build a solid foundation in this course we will cover the introduction of JavaScript then we will see the basics of JavaScript where we will learn about the variables scope operators keyword reserved keywords and expression then we will see the data types and after that we will see the difference between primitive and reference values then we will move to operate s where we will learn about the arithmetic operator assignment operator logical operator comparison and then we will move to control flow statements where we will learn about if if else statements for while and do while loop and break and continue statement after that we will see the functions functions are important Concepts in JavaScript so in the function we will learn about the function parameters arguments return keyword in the function then we will see the anonymous function recursive function and default parameters after that we will learn about the objects and prototype where we will learn about the key values and method in the object then we will see the Constructor function prototype object D structuring and object literal syntax extensions after completing the object we will learn about the classes classes are also very important in JavaScript so in the classes we will learn about about the class getter and Setter methods then we’ll see the class Expressions inheritance static methods and private methods after completing the classes we will move to the Dom which is document object model so in this Dom we will learn about the notes then we will learn about get elements and query selected methods then we will see the create and clone element then we will learn add nodes to document then we will see get elements details using the Dom then we will learn about the modifying element using Dom then we will see get and modify the element class using the Dom then we will learn about the events available in this Dom each concept is clearly made to be beginner friendly with clear explanation and practical examples along with this I will also provide you the complete notes of this course in the video description but here is the best part it’s not just Theory at at the end of this tutorial we will make some real world projects like online Notes app Quiz app form validation image slider digital clock and e-commerce product page don’t worry you will not need any prior coding experience before starting this course by the end of this course you will be writing JavaScript code with confidence so are you ready to master JavaScript hit that subscribe button and help me to get the 5,000 likes on this course now let’s dive into the world of JavaScript together welcome to JavaScript introduction tutorial in this tutorial we will learn what is Javascript why you should learn JavaScript what is the use of JavaScript and how to write your first JavaScript program so what is Javascript JavaScript is a scripting language that is used to create interactive and dynamic websites interactive website means user can perform some action on website for example button click submit a form write comments and live chat Dynamic website means the website that changes its content or layout like sliding effect e-commerce website and quiz website why you should learn JavaScript JavaScript is the most popular programming language in the world it is used in almost all popular websites like Google Facebook Twitter Amazon Netflix and many others great thing about JavaScript is that you will find tons of Frameworks and libraries to reduce your time to create websites and mobile apps some of the popular Frameworks are react angular and vuejs if you learn JavaScript it opens a lot of job opportunities in the software development Industries what what is the use of JavaScript uses of JavaScript is not only limited to front-end web development it is also used in backend web development mobile app development desktop app development game development and API creation using JavaScript you can easily create websites like Amazon and Netflix mobile apps like Instagram and WhatsApp games like Tic Tac to and snake game you can also create mini JavaScript projects like to-do list app Quiz app Notes app weather app calculator or image gallery I already have 30 mini JavaScript projects on my YouTube channel that you can check out from the link given in the video description and these projects are more than enough to learn and practice JavaScript how to write your first JavaScript program to start with JavaScript you need to have a web browser and a code editor I’m using Google Chrome web browser and visual studio code editor I already have a tutorial how to download and install Visual Studio code editor you can find the video link in the description so let me open my code editor here I have one HTML file with basic HTML structure in this HTML page you can see we have the head open tag and head closing tag and this is the body open p and closing tag so the first option is to add the JavaScript code within the head tag so before closing of this head tag we can add our JavaScript code so let me add one a script tag a script open and closing tag like this and within this script we can add our JavaScript code so let me add one line of JavaScript here alert welcome to greatest stack this JavaScript code will give instruction to browser to alert this message welcome to greatest stack so let’s open this web page you can see this message welcome to greatest tack click okay so this was the first option to add the JavaScript code in the SML file now the second option is to write the JavaScript code within the body tag let me remove this script from here we have to add the code within this body tag so I will add it here a script open and closing tag within this we have the JavaScript code to alert one message welcome to greatest tag now let’s open the web page again and again you can see this message welcome to greatest tag so this JavaScript code written within the body tag is also working now let me remove it from here also there is another option to add the JavaScript code in the HTML file that is external Javascript so to add the external Javascript we will use a script SRC and the new file name so here let’s create a new file name and write the file name script.js you can write your own file name but the file name extension should bejs I’m writing a script.js you can write main.js index.js anything so this is the new file script.js and next we have to add this file here a script SRC and the file path a script.js so we have added the file path here now let me open the folder in this intro folder you can see there was one HTML file and now we have one more file the script.js and we have connected the script.js with the HTML file with thist script tag and now we can add our JavaScript code within this external file so here we will add alert welcome to greatest tag after adding this let’s come back to the website and now you can see this alert message welcome to greatest tag so this JavaScript code is also working now let me come back to the HTML file and we can move this a script tag in the head also like this and it will also work you can see this alert is working let me place it here within this body tag there are multiple options to display the output of JavaScript on the web page or browser so here I have added alert welcome to greatest T so we can see the message in the alert box there’s another option we can add document dot write welcome to greatest stack we can write like this document. write so it will write this message in the web page let’s see our web page you can see this message welcome to greatest tack it is written on the website now we have one more option here if I write console do log this will give the output in the browser console tab so let me show you come to this browser right click and select inspect it will open this developer tool and here you have to click on Console let me Zoom it click on Console we can change the theme by clicking on this setting icon appearance and do so this is the console tab here you can see this message welcome to greatest tag because here I have added console.log welcome to greatest tack if I change the message JavaScript tutorial come back to the website you can see welcome to greatest Tech here because I have added document. write and here you can see JavaScript tutorial because I have added console.log so it will add this message in the console Tab and in this console also we can add our JavaScript code we can write and execute the JavaScript code within this console tab also so let me show you one example if I write 4 + 5 and we got the result 9 so it is executing the JavaScript code here let me add one more thing if I write console dolog hello and hit enter you can see we have added console.log Hello and it is printed here hello now if you want to display the output on the browser alert box we can write like this alert hello hit enter you can see this alert box with the message hello now you can display the output on the website also let me add document dot WR and here we will add the message hello click enter you can see the Hello message on the website so this is how you can display the JavaScript output on your website or browser console and now you know how to write your JavaScript code so this was all about JavaScript introduction and writing your first JavaScript program what is variable in JavaScript variables are used to a store data it is like a container where we use to store things at home to declare a variable in JavaScript we use the V let and const keyword we can write where X here where is the keyword to declare a variable and X is the identifier or name of the variable we can also declare variable like let X or const X the V keyword is the oldest and the most common way to declare variables theet keyword is a newer keyword that was introduced in es6 we will learn about es6 later in the advanced JavaScript the const keyword is used to declare constants which are variables that cannot be changed once you have declared a variable you can assign a value to it using using equal sign for example where xal to 30 the following code declares a variable called X and assign it the value 30 variables can be used to store any type of data including number a string objects and arrays for example if I write where x equal to double quote or single quote any message hello world so here we are storing the string data type in the X variable variables name must begin with alphabet dollar sign or underscore if I write 2x it is not a valid name for the variable if I write anything in the alphabet it is valid and we can also declare it with the dollar sign we can start like this dollar X it is valid and we can also use underscore here like this underscore X let me remove it so you can see it is valid format to write a variable name you can start with dollar and you can start with any alphabet in upper case or lower case it is valid but if you start from the number it is not a valid name for the variable if you add the valid character then later you can add number it is valid JavaScript is case sensitive so if you write where first name equal to greatest stack and if you write first name with the lowercase end so these two variables name are different it is not same because here we have the different case so JavaScript is case sensitive that’s why it is two different variables name now let’s understand about the let keyword let keyword in JavaScript is used to declare a block scoped variable this means that the variable is only visible within the Block in which it is dict cleared for example if I write let x equal to 10 and if x greater than 5 yes it is greater than 5 because the x value is 10 in this block we will add let y = to 20 and here if I try to display the value of y we will add console do log y so you can see this y value in the console tab here you can see 20 correct we have added this code within this curly bres so it’s a block and if I try to access this y outside of this block we will copy this and paste it here here outside of this block and now if I try to run it you can see one error reference error why is not defined so if you try to access the Y value outside of this if statement you will get a reference error this is because variable Y is not defined outside of this block now let’s understand about the const keyword so the const keyword in JavaScript is used to declare a con Conant variable this means that the variable cannot be reassigned to a new value for example if I write const a equal to 4 so we are assigning a value for in the a variable now if I print this console do log a we will get four in the console tab now in the next line if I try to write AAL to 5 we are trying to reassign a new value a equal to 5 and run this you can see we got an error assignment to constant variable so we cannot assign a new value in constant variable now let’s learn about the scope in Java JavaScript scope in JavaScript refers to the visibility of variables and functions within a program in JavaScript there are three type of a scope Global scope function scope and the third one is block scope so let’s learn about the global scope the global scope is the outermost scope in the JavaScript program variables and functions declared in the global scope are visible from anywhere in the program let’s understand it with one example if I write where x equal to hello greatest stack and here we create one function called example and in this one if if I try to print this message if I write console do log X and now we have to call this function example now you can see this message in the console tab hello greatest stack over here in this example we have declared a variable X outside of any function or block which makes it a global variable Global variables are accessible from anywhere in the script including inside a function and we have declared this outside of the function so we can access it within the function and outside of the function also if I simply add this here and it will also print this you can see Hello greatest stack two times the first one is printed using this console.log written inside the function and the second message is printed using this console.log x so this was the global scope now let’s understand what is the function scope so the function scope is created when a function is declared variables and functions declared in a functions scope are only ual within that function so let’s understand this function scope with one example here we will add function example here we will create one variable where FS function scope equal to hello greatest stch and if I try to display the output we will add console. log fs and now just call this function so now you can see this message hello greatest TCH because we are accessing this variable inside this function now if I try to access this FS outside of this function let’s copy this and paste it here outside of this function and try to run it we got an error FS is not defined why because we have defined this FS variable inside this function so it is a function scope variable and now we are trying to access this FS outside of this function it is not accessible so the variables and functions declared in a functions scope are only visible within that function now let’s understand the block scope so the block scope in JavaScript refers to the visibility of variables and functions within a block of code a block of code is a group of statement that are enclosed in a curly braces variables and functions declared in a block scope are only visible within that block let’s understand block scope with one example let’s create one function and in this one we will create one block true and here we are creating one block with this curly bres So within this if we will add one variable so let’s add the variable name block variable BV equal to create a stack and here if we try to display this console.log BV and just call this example now you can see this message greatest stack in the console tab here because we are accessing this variable inside this block now if I try to access this variable outside of this block it is declared inside this block and if I try to access here this block is closing here so let’s add this line here at line number n and now if I try to run you can see we got an error in line number nine BV is not defined because we are accessing this variable outside of this block let’s try to access this variable outside of this function only let’s remove it from here and add it here at the end and now you can see the error message at line number 12 BV is not defined because we are trying to access this variable outside of this block so the variable and functions declared in a block scope are only visible within that block so this was all about the variables and the scope in JavaScript data types in JavaScript data types is an important Concept in any programming language to perform any task with the data it is important to know its type data types in JavaScript are divided into two categories primitive data type and reference data type there are seven primitive data types in JavaScript which are a string number buo null undefined big int and symbol so let’s learn about the string data type in JavaScript a string is a sequence of zero or more characters a string starts and end with either a single quote or a double quote JavaScript strings are for storing and manipulating text for example if I write let first name equal to double code elone so here we are adding one name in double quote it is a string and the variable name is first name let me duplicate it here we will add last name and if I write the text in single quote musk it is also a string it is written in double quote and this is written in the single quote now let’s see another data type which is number number represents integer and floating Point numbers for example if I write let num equal to 100 in this statement we have declared one variable called num and initialized its value with the integer 100 let me change the value if I write 96.5 it is also a number type here we have stored the floating number if we write 96.0 then JavaScript will convert it into an integer number to use less memory so it will be saved only 96 let me show you that if I write console.log num so you can see 96 is printed here it is not printing 96.0 it is printing 96 only because the JavaScript is converting this floating number into an integer and if I type 96.5 it will be saved as 96.5 and if we change 96. it will be only 96 now let me tell take another example if I write let x equal to 10 so here I have stored one number in the X variable let me write console.log X here we will get 10 in this console tab we got 10 now if I add a single quote in this 10 now it will become string because we are adding single quote in this text now if I print this one you can see still it is displaying 10 but if you will check the data type it will be a string the value is 10 but the data type is a string to check the data type we have one operator called type of in front of this variable name if I write type of X you can see we got the data type string because this 10 is written inside the single quote if I change it and make double quote still it will be string you can see string here now if I remove this quote and if we only write 10 then it will be a number you can see it is number when we will add double quote or single quote it will be stored as a string now the next data type is Boolean the Boolean data type has two values true and false let’s understand it with one example if I write let learning equal to true and and let completed equal to false here we have stored Boolean data in the learning variable and completed variable now to check this one we will add console.log learning you can see true so it is display the value stored in this learning now to check the type of the data stored in this learning we will again use the type of operator type of learning so it is displaying the data type Boolean now let’s check the data type of this another variable which is completed just copy this one add it here here it will display the data type Boolean for the another variable called completed now if you want to display the value stored in this completed here I’m adding console.log completed and it is displaying false here which is the value stored in the completed variable and it is the type of the value which is Boolean so we have stored the true or false value directly but we can store the result of any expression for for example if I write let X = to 20 greater than 10 so the result of this is true 20 is greater than 10 it is true so now if you want to check the value stored in the X we will add console.log X and now you can see it is displaying true here we are writing 20 greater than 10 but the X has stored the result of this expression which is true now if I change if I write 20 less than 10 which is false so you can see the result in the console tab it is displaying false so we have stored the false in the X variable now let me show you the type of the data here we will add type of X and now it is displaying Boolean so this x has a store the Boolean data type next primitive data type is undefined if a variable is declared but the value is not assigned then the value of that variable will be undefined and the data type is also undefined let me show you this with one example let H we have declared a variable age but we have not assigned any value now we will check the value stored in this age let’s add console.log age here you can see the value is undefined now if you want to check the type of the data here we will add console.log type of age now you can see the value is also undefined and the type is also undefined if we add any value like this a is 30 now you can see the value is 30 and the type is number and when we remove it we have not assigned any value so the value is undefined and type is undefined so this was undefined data type next pleas primitive data type is null in the JavaScript null is a special data type that represents empty or unknown value let’s understand it with one example here if I write let number equal to null and now we will try to print the value here we will add console log number so you can see the result it is displaying null now we will try to display the type of the data so here in the next line we will add console.log type of number you can see the value is null but the type is object the type should be null but it says the type is object it is a known bug in JavaScript JavaScript defines that null is equal to undefined to check this one we will write console.log null comparison operator then undefined so we are comparing null with the undefined and here you can see we got the result true it means in JavaScript null is equal to undefined there are two other primitive data types which are symbol and B that we will study in our upcoming videos now let’s learn about the reference data type so the first reference data type is object in JavaScript an object is a collection of properties where each property is is defined as a key value pair so let me create one object here if I write let person equal to curlys that’s it so the following code defines an empty object this is the person object which is empty now let me display the data stored in this person object for that we will add console.log person that’s it now you can see we got the empty curly bles now to check the type of the data we will copy this one and here we will add type of person so you can see the result the data is empty in this curly Braes and the data type is object now let’s add some properties in this person object here we will add first [Applause] name last name and age let’s add 35 so you can see in the console tab the data type is object and this is the data stored in the person object first name Elon last name musk age 35 an object can store different data type in this person object the first name and the last name are string and this age is number so this person object can store different type of data it can also store another object our next reference data type is array arays are a type of object that stores a collection of values for example if I write let number we have have added five different number separated by comma in the square bracket so the following code creates an array of numbers now let’s print the value of this number we will add console.log number so in the console tab you can see this aray is printed 1 2 3 4 and 5 the same thing is printed here now if you want to check check the type so let’s add this line again and in this one we will add type of operator type of number now you can see in the console tab we got the type object so the array is also an object data type our next data types is function functions are a type of object that can be used to execute code for example here we will create one function to create a function we use the function keyword and the name of the function so let’s add the function name MSG that is for the message and in this one just add one console.log and here we will add one string hello greatest tag so we have declared one function with the function name MSG now if you want to check the type of the data here we will add console.log type of MSG that is function name and if I check this in the console tab you can see it is displaying function it says the type of data is function but it is also an object data type Javas script is a dynamically typed language so we can store different data type in the same variable for example if I write let X here we are not assigning any value so the data type will be undefined so let’s check this one type of X it is displaying undefined let’s check the value also if I write console.log X console.log type of X so it will display the value stored in the X and it will display the data type now you can see in the console tab it is displaying the value undefined and data type undefined now in the same variable we can store different data type here we have already declared the variable so we will just add X we are not declaring we are just assigning the value x equal to let’s say one string greatest tag so here we are adding one string in the X variable let’s try to to print this you can see in the console tab it is printing undefined and undefined from here now we have changed the data it is greatest tag which is string so you can see the value and the data type is a string now again we can change the type of the data we will simply store another data let’s add x equal to 100 so here we have stored the number let’s try to print this now you can see in the console tab we have the value 100 and we have the type number so earlier it was undefined then it is a string then it is number now let’s add one more example if I write X true and in the console tab you can see it is true and the data type is Boolean so the JavaScript is dynamically typed language so we can store different type of data in the same variable and in this one you can see the example also it is undefined it is string it is number it is Boolean so this was all about the data types in JavaScript operators in JavaScript operators in JavaScript are symbols that are used to perform operations on operants operant are the values and variables so let’s understand it with one example here if I write 10 + 20 here plus is an operator and 10 and 20 are operant here is the list of different operators that we will learn in this tutorial arithmetic operators assignment operator comparison operators logical operators and string operators now let’s learn arithmetic operators arithmetic operators are used to perform mathematical operations on operants there are multiple arithmetic operators so first one is addition here we will add let sum equal to 5 + 3 and console.log sum so in the console tab you can see we got the sum which is 8 5 + 3al 8 this is the addition operator now let’s learn the second one which is substraction here we will add substraction it will be x 5 – 3 three it will be X now you can see two in the console tab because 5 – 3 is 2 so this is the substraction now the next one is multiplication if I write five multiply 3 now you can see the result 15 now the next one is division operator for division views forward slash let’s add 15 ided 3 now you can see the result 5 15 / 3al to 5 now the next one is reminder or modulus here we will add modulus and to get the modulus we use percent symbol and and if I write 17 perc 4 now we will get the modulus 1 you can see when you divide 17 by 4 you will get the reminder 1 which is modulus now the next arithmetic operator is exponentiation when you write 2 to ^ 4 2 to the^ 5 that is exponential so to calculate the exponential here we will add X two double star and four so it means we will add 2 into 2 into 2 four times like this so what will be the result you can see in the console tab 16 so if you write dou star it will be exponentiation operator so these are arithmetic operators now let’s learn about the assignment operator assignment operators are used to assign values to variables we use equal sign to assign operator for example let X = to 5 here we are using equal sign which is the assignment operator and we write the value on the right side of the operator so this was the simple assignment M operator now we have other assignment operator also like addition assignment so let’s see that we have the x value 5 now we will add X Plus equal to 3 so if you simply add x = 3 it will replace the value in this x variable and the X will become three but here we are adding plus it means this three will be added in the existing value of this x so the current value of x is 5 and 5 + 3 will be 8 let’s check the output console. log X and in the console tab you can see the value8 so this was the addition assignment similarly we have the substraction assignment here we will add minus equal to 3 now we will get the output two you can see the output 2 now we have the multiplication here we will add multiply 3 so this three will be multiplied with the current value which is 5 5 into 3 and now you can see the output 15 next one is division assignment you can see this value here after that we have the modulus assignment you can see see the modulus 2 now the next one is exponentiation assignment dou star equal to 3 it means we are writing 5 to the^ 3 and it will be 5 * 5 * 5 so the result is 125 now let’s learn about increment and decrement operators the increment and decrement operators are used to increase or decrease the value of a variable by one suppose the variable value is five it will be incremented by 1 and it will become six or it will be decremented by one it will become four the increment operator is Plus+ and the decrement operator is minus minus increment and decrement operators can be used in two ways which is prefix and postfix so let’s learn prefix increment and decrement operator let me add one example here let a equal to 10 in the next line I’ll add console. log Plus+ a we are adding increment operator before the variable name which is a now you can see the output 11 because the value of a has been incremented by one now let me add one more line console.log a so in this line the value of a is incremented by 1 then it is printed 11 and in this line the current value of a is printed the current value is 11 in this example operator is placed before the variable and the value of the variable is increased before it is used now let’s see prefix decrement operator so for decrement we will add minus minus and in the console tab you can see the output 9 and 9 so it is decreasing the value of a by 1 then it is printed here and in the next line we are printing the current value of a which is 9 now let’s learn about the postfix increment and decrement operator in the postfix we add the operator after the variable so if I remove this and add Plus+ after a now you can see the output first it is printing 10 and after that 11 here we are adding A++ but still it is printing 10 because a is printed first and after that it is increasing the the a value by one now the next time I will print the a value it will display the updated value here it is displaying 11 in this example operator is placed after the variable and the value of the variable is used before it is incremented the same thing will happen with the decrement post fix operator if I run this one you can see current value of a is 10 and first it is printing the value 10 after that it is decreasing the value by one and if I print the new value of a it is N9 so this was the increment and decrement operator now let’s learn about comparison operator comparison operators compare two values and give back a Boolean value either true or false comparison operators are useful in decision- making and loop programming in JavaScript let’s see some example if I write like this it will be the less than operator it is greater than this will be less than or equal to this is greater or equal to this will be equal check it will check the equality of two values it will be inequality or not equal and it will give the flip value of the equal checks we will understand it with the example also and this one is the strict equality check it checks the data type also I will also explain it with example and it is the strict inequality or flipped value of the strict equality check now let’s understand these comparison operators with example here if I add let a = to 10 b equal to 20 and here we are adding less than operator you can see console. log a less than V so it will give the result true in this one it is checking a greater than b which is false a is 10 B is 20 so a greater than b is false so it will give the result false now it is a less equal to B so it will be true and this will be false a greater or equal to B it is false because a value is 10 now here we are checking a equal equal B it means a value is equal to B is not equal it is 10 and 20 so it will be false in this not equal we will get the flipped result of this equality check so the equality check was false so this will be true and this is the strict equality check and this is the strict unequality check so let’s print this one you can see the first one is true a less than b true a greater than b false a less than equal to B this true a greater equal to B it is false A = to B 10 = to 20 which is false a not equal to B so it will be true now in the next line we are adding a strict equal so A and B is 10 and 20 it is not equal so we will get false and it will be the opposite it result true now let’s understand it with other example if I remove this and here if I write like this 10 and it will be 10 so a is 10 as a string and B is 10 as a number now let me add one more thing here console.log a equal equal B now you can see the first one is true why a is 10 B is 10 then it is true now in the next line we are adding a triple equal to V it is giving false why first it will check the data type so in this one the data type is a string and the data type is number in the B variable then it is different so it is not equal so that’s why it is giving false and the last one is giving true because it will give the flipped value of this false our next topic is logical operators logical operators perform logical operations like and or not for logical and we use this symbol for logical or we use this symbol and for logical not we use this exclamation symbol so let’s learn about the logical and logical and evaluate op and return true only if all are true in this line you can see the first condition is true and the second is true and here we are adding logical and operator so both are true that’s why the result will be true now in this one the first one is true second one is false so both conditions are not true that’s why it is false here also one of the condition is false it is false here both conditions are false that’s why it is false only when both conditions are true then only the result will be true now let’s understand logical and operator with one example here I have added let X = to 5 and y equal to 10 and I’m adding X greater than 0 so this condition is true X is obviously greater than z y is also greater than zero then the first condition is true second is also true then the result will be true you can see the first result is true now in the second condition you can see X greater than 0 which is true y less than 0 which is false 10 less than 0 is false right then one of the condition is false that’s why the result is false now in The Third One X less than Z which is false then the result will be false and in the last one 5 less than 0 is false and Y isal to 10 which is 10 less than 0 which is false so both conditions are false that’s why the logic result is false so this was The Logical end now let’s learn about the logical or logical or returns true if one of the multiple operant is true if any one oper is true then it will return true so here you can see the first one is true true and second one is true so the output will be true first one is true second is false still the output is true first one is false second is true then the output is true in the last one first condition is false and second condition is also false then the result will be false so if all operant are false then the output will be false and if any one of the operant is true the result will be true now let’s understand this logical or with one example here we have the a value 5 b value 10 and a greater than Z true B greater than Z true so both conditions are true then result will be true now here the first one is true this is false then still it is true it is false it is true then still it is true now in the last one for first one is false second one is false so both operant are false so the result is false so this is the logical or operator now let’s learn about The Logical not logical not converts operator to Boolean and return flipped value let’s understand it with one example if I write let yes is equal to True let no equal to false we are adding two variable yes and no and yes is true no is false and if I try to print not yes not operator and yes then it will give the flipped result earlier it was true now it will display false you can see the first one is false here in the second one we are adding not no so the no value is false so the not no will be true you can see the not no is true so this is The Logical not operator our next topic is Javascript string operators in JavaScript you can also use plus operator to concatenate or join two or more strings let me explain this with one example if I write console.log and in this one in this one we will add two string let me add hello Plus World and let’s see the console tab you can see hello world is printed here if you need one space we will add it here now you can see it is printed with one space hello world we we can join the string using the addition assignment operator Also let’s see another example if I write let a equal to JavaScript and in the next line I will add a addition assignment operator plus equal to and here we will add another text so let’s add a space tutorial in the current value of a the current value is Javascript and in this JavaScript it will add this tutorial let’s print it in the console you can see this text JavaScript tutorial is printed in this console tab so this is how you can join or concatenate strings in JavaScript using the plus operator so this was the string operator in JavaScript there’s one more operator in JavaScript which is bitwise operator bitwise operators are rarely used in everyday programming that’s why we will skip this one our next topic is operator precedence operator precedence in JavaScript determines the order in which operators are passed concerning each other let me take one example let result equal to 2 + 3 * by 4 so what will be the output here if you add 2 + 3 it will be 5 and 5 * by 4 it will be 20 so this will be output or it will will be 4 * by 3 12 + 2 = 14 so which is the correct answer so the correct value is 14 let me show this result in console tab now in the console tab you can see the output 14 why because the 3 * by 4 is performing first and after that it is adding two so why multiplication is performed before addition it is because of the operator’s precedence value in this table you can see the Precedence of multiplication and precedence of addition so the higher precedence is performed first that’s why it is multiplying three and four after that it is adding two and the result is 14 so this was operator precedence now let’s learn about Operator associativity Operator associativity in JavaScript defines the order in which operators of the same precedence are evaluated there are two type of operator associativity left to right right to left in this table you can see the operator name and their associativity now let’s learn about the left to right associativity in left to right associativity operators are evaluated from left to right let’s take one example if I add let result equal to 4 – 2 – 1 in this example only substraction operator is used and its associativity is left to right as you can see in this table the expression 4 – 2 – 4 is evaluated from left to right first 4 minus 2 will be evaluated and it will give the result 2 then 2 – 1 will be evaluated and it will give the result one so let’s check the result in the console tab you can see the result one so this was left to right associativity now let’s learn about the right to left associativity in right to left associativity operators are evaluated from right to left for example let result equal to two exponentiation 3 exponentiation 2 in this example only exponentiation operator is used and its associativity is from right to left as you can see in this table first three exponentiation 2 is calculated resulting in N then 2 exponentiation 9 is evaluated and giving the result 500 12 so let’s see the result in the console tab here if I write log result you can see the result 512 so this was all about the JavaScript operators control flow statements in JavaScript control flow statements are used to control the flow of execution in JavaScript program they are used to make decisions execute loops and handle errors there are three type of control flow statements in JavaScript which is conditional statements loops and try catch statements so now let’s learn about conditional statements conditional statements are used to execute different code based on different condition the most common conditional statements in JavaScript are are if a statement else a statement and else if a statement if a statement in JavaScript is used to execute a block of code if a condition is true so let’s understand it with one example here we will add if and in this parenthesis we will add one condition condition will be true or false so we will add true in this block let’s add one line of code execute so in the console tab you can see this message execute in this example the condition is true that’s why it is executing this code and it is printing execute in this console tab now if I change it here we will add false and now in the console tab you can see nothing is printed why because if the condition is false then any code written within this block will be skipped it will not execute now let’s understand it with another example here we will add age greater than 18 and let’s add let age equal to 20 and and it will print one message you are an adult so here we have the age value 20 and the condition is age greater than 18 so you can see 20 is greater than 18 that’s why this block of code will be executed and we will see this message here now if we change the value of this age let’s add 16 now in the console tab you can see it is blank nothing is printed why because this condition is false 16 greater than 18 is false that’s why this code will not be executed let me comment this and we will take another example and here let’s understand with another example we will add let country equal to India and let age equal to 20 if age greater equal to 18 and operator country equal to India so this is the if statement where we are adding two conditions using the logical and operator here we are adding logical and that’s why if the first condition is true and second condition is true then only this complete line output will be true so you can see the age is 20 which is greater than 18 and country is India and here it is comparing with India so this condition is also true and this is also true then overall result is true so we can print any message console.log you can get a driver’s license now you can see it is printed here in this console tab you can get your driver license now if I change the age value to 17 now nothing is printed in this console tab it is empty so you can add this type of logical or logical and operator to get the true or false value and then if the value is true then only this code will be executed now let’s learn about the if Elsa statement if Elsa statement in JavaScript is a conditional statement that is used to execute a block of code if a condition is true and another block of code if the condition is false so let’s understand it with one example here we will add the same example here you can see if the condition is true then only this code will be executed now we have to add another statement that will be executed when the condition is false so here just add else in this else condition I will print another message console.log you a minor now you can see in in the console tab we got an message you are a minor why because the age is 18 so the if condition is false here we are adding 16 greater than 18 which is false so if it is false then else condition will be executed and if I change the value 19 you can see the message you are an adult the if condition is getting executed next conditional statement is else if so in this example we have one if condition and one else condition now we need another condition also so here we will add else if and in this one let’s add one condition check here we will add age greater equal to 16 it will be greater equal to 18 and in this else if let’s print one message console.log you are a teenager so what will happen in this program first it will check if it is 19 this if condition will be executed now if this condition is false suppose the value is 7 1 now it will jump to the next statement the first one is false it will come to the next statement which is else if and in this one it will check whether the condition is true or false if the condition is true then only this code will be executed else it will go to the another statement so here let’s check age is 17 and 17 is greater than 16 correct so that’s why this condition is true then this code will be ex uted now let’s check this one and you can see in the console tab we got the message you are a teenager it is printing from this console.log which is in the else if statement like this you can have multiple else if a statement suppose this is also false let’s add 15 age is 15 so this condition is false this condition is also false so it will execute the else condition condition else condition is ur minor you can see in the console tab the message Ur minor now you know the if statement else if statement and else statement now we will learn about this switch in JavaScript the switch statement in JavaScript is a conditional statement that is used to execute a block of code based on the value of an expression let’s understand the switch with one example here if we write let value is equal to 42 and then we will add the switch statement so this is the syntax to write this switcher statement in this one we will add type of value so it will get the type of this value variable and the type is number for now now in this case we will execute different message we can create multiple cases so in the first case let’s add number so if the type is number then we will print console.log number we can add multiple case so let’s duplicate it and here we will add string console.log string let’s add another one it will be Boolean console.log bullion in the default we will add console.log other now in this switch statement you can see the output is number why because we are adding value is equal to 42 which is is the number type and here it will check the case if it is number then it will print number now if we change the type if I add hello so the type of this variable is a string so it will check this case it is not correct then it will check this case so the type is a string correct that’s why it is printing this message now if I change it let’s add true so the type is Boolean so this case will be executed and it will print Boolean now if I add anything else let’s add one array now you can see other is printed here because this case is also false this is also false this is also false so it will print the default one so in this default we have added message other that’s why it is printing other in this console tab now let’s take another example of this switch case here we will add day name and the day name let’s add two suppose the day start with Sunday Monday Tuesday and the number is 1 2 3 for Sunday it is 1 Monday it is two so here we are adding let day name is equal to two now let’s add the switch statement went went in this one we have to pass the day name so let’s add switch day name as a key and here we will add different values so first value will be one and here day name is equal to Sunday now we will add second case case 2 so the day name will be Monday let’s add case three so we have added seven different Case Case 1 2 3 4 5 6 7 and name of the day wednessday Thursday Friday Saturday suppose we have entered Any number greater than 7 then we will display another message so here in this default we will add day name is equal to invalid day number now to print this we will add console.log let’s add the message the day is plus day name this is the string and this is the variable now in the console tab you can see the day is Monday why because we have added day name two now let’s change it here we will add five and we will check the console tab you can see the day is Thursday let’s add seven so it will check this case one then it will check two then it will check three so it is seven so it will come here case and the value is seven then day name will be Saturday and it will be printed using this console the day is Saturday so this is the switch case statement in the JavaScript now we will learn Turner operator it also works like if else a statement let me write the example of if else a stat M so here we have added let age equal to 20 if a greater than or equal to 18 so if this condition is true this code will be executed and if this condition is false then else statement will be executed now the same thing we can execute using the Turner operator for Turner operator we use this question mark now let’s see the Syntax for the Turner operator first we will add condition then question mark and after this question mark we will add the code that will be executed if the condition is true so here we will add value if true now we will add column and here we will add the code that will be executed if the condition is false value if false this is the syntax to use the Turner operator now let’s understand with example so here we will add the same thing let age is equal to 20 and now we will add the condition like this age greater equal to 18 question mark if it is greater then what we will print we will print Ur an adult this will be the message and if it is false this condition is false then we will print you are a minor we can directly write console.log and this message so it will be printed in the console tab so this will become so long that’s why here I’m adding let MSG is equal to this either this message or this message will be stored in this MSG now we will add console.log MSG let’s see the output in the console tab you are an adult now if I change the value it will be 16 now check this you are a minor so this is how the Turner operator is working same as the F statement so this was all about the conditional statements Loops in JavaScript in programming Loops are used to repeat a block of code for example if you want to display a message 100 times then you can use a loop first we will learn about the for Loop syntax of the for Loop is this one you have to add for then in this parenthesis we are adding the initial value of I after that we are checking the condition if this condition is true then only this code will be executed and after execution of this code written in this curly reses it will increase the value of I by 1 now let’s understand the for loop with one example suppose I want to print one message 10 times for that here let’s add console.log and in the message I will add greatest stag so I want to print this greatest stack 10 times let’s start it with one initial value of I is 1 and I want to print this for 10 times so here we will add less than equal to 10 this is simple now if I run this code you can see Greatest Tag is printed 10 times you can see 10 here we are printing the same message 10 time that’s why the browser will collapse it and display only one line and here it will display 10 it is printed 10 times now let’s take the another example of for loop I want to print number from 1 to 10 for that this for condition will be same here we will just add I so first what will happen the I value will be one and it will be printed using this console. log I after that it will increase the value so the I value will be 2 and it is less than 10 right then it will print two again it will increase the value that will be I3 and IAL to 3 is less than 10 so 3 will be printed so like this it will be printed up to 10 now run this code and you can see 1 2 3 up to 10 is printed in this console tab we can use Loops for printing the data of an array let’s take another example let me comment it and here I will add let coding equal to one array and in this array I will add JavaScript python C++ now I want to print the JavaScript Python and CPP using for Loop to get the element we use the index so index I start with zero JavaScript is at zero index python have index one CPP have index two so let’s write the for Loop here we will add for let’s add let I is equal to 0 because index starts with zero now I will be less than the length of array so this is the array dot length so AR length is three maximum index value is two that’s why I’m adding I less than coding do length that is 3 I Less Than 3 after that we will add i++ and in this C adds we will add the code that has to be executed every time so here we will add console.log coding and I first it will execute coding zero then coding one and coding two so coding zero will display JavaScript coding 1 will display Python and coding two will display CPP so you can see the output in this console tab JavaScript Python and CPP so you can use the loop on ADD also we can create another loop inside a loop let’s see another example here we already have this code this is the first Loop and let me make it small I’ll add one to five and it will print the number from 1 to 5 and after that we will add another loop inside this Loop here we will add for and here we will add another variable name let’s add let Jal to 1 so initial value is 1 next we will run this Loop for three times so here we will add J less than equal to 3 then increase the value of J and in this we will print another message let’s add console.log and here we will add one message inner loop plus J now you can see the output in the console tab first it will execute this code and after that it will come to this for Loop now this for Loop will be executed for three times and in three times it will print inner loop one inner loop two inner loop three here we will add a space so you can see inner loop 1 2 3 now again it will increase the value of I so I will be two and this will be printed console. log I so 2 will be printed in the console tab you can see two is printed here and after this again this for Loop will be executed and it will again print from the 1 to 3 you can see 1 2 three now again the I value will be increased by one it will be three and three is printed here and again it will execute this inner loop now you can see the message inner loop 1 2 3 again the outer loop will be executed console. log I I will be 4 so this is how you can use another loop inside a loop now we will learn while loop syntax of while loop let’s add V and in this parenthesis we will add condition then in this curly Braes we will add the code that has to be repeated so this is the syntax of while loop which is very simple so in this one we have to add one condition and this code will be executed until the condition is true when the condition is false it will stop the loop now let’s understand the Y loop with one example we will print number from 0 to 10 so here let’s add console.log let’s add I and we have to declare this I so here we will add let I equal to 0 because we have to print the number from 0 to 10 now in this condition we will add I less than equal to 10 so first it will check the I value I value is zero so if the value is less than 10 then it will print the value of I now it will print the same value again and again so we have to increase the value so in the next line we will add i++ so first it will print the value then it will increase the value now you can see the output 0 1 2 up to 10 so this while loop is repeating this code until the I value is less than or equal to 10 suppose the I value is 10 so 10 less than equal to 10 is true it will print this value that is printed here now it will increase the value by 1 so I will become 11 now it will again go to this condition and 11 is less than equal to 10 that is false once it is false then it will stop this Loop next we will learn do while loop do while loop is also very simple so this is the Syntax for do while loop first it will execute the code written in this do statement and after that it will check the condition if the condition is true then it will again execute this code and when the condition is false it will stop this Loop now let’s understand it with one example let’s write one code to print a number from 1 to five using do while loop so here we will add let IAL to 1 and it will print using console tab console.log I and here it will check the condition we will add I less than equal to 5 here we have to increase the value of I so let’s add i++ now you can see the output in the console tab 1 2 3 4 5 so first the I value is 1 then it will come to this statement and it will print the value of I 1 then it will increase the value by 1 so it will become two so 2 is less than equal to 5 that is true so again it will print the value so it will be printed here then it will become three and 3 is less than equal to 5 that is also true again three will be printed here like this it will print one to five series now let’s change the value of I to 10 if I add IAL to 10 you can see the output 10 is printed here why it is printed because do Loop will execute the code first time then only it will check the condition so first it will print the value of I I isal to 10 so console. log I will be printed here 10 then it will increase the value 11 then the value of I will be checked here I less than equal to 5 which is false so it will not execute the code again but the first time it will be printed so this was for Loop while loop and do while loop apart from this there are some other Loops also like for off for in that we will study in advanced JavaScript now we will learn about break and continue statement in JavaScript the break statement is used to terminate the loop immediately let’s understand this with one example let’s take one example of for Loop for printing 1 to five number this for Loop is printing number from 1 to 5 you can see in the console tab now if I add one if condition here before printing this number here we will add if I comparison operator three when the I value is three then we will add break so you can see what will happen when it will get the break statement it will terminate the loop it will stop the loop you can see in the output only one and two is printed first time the I value will be printed then second time the I value will be printed that will be two then third time I will be three and here it will be checked if I is equal to 3 it will get this break statement and after that it will terminate the loop only IAL to 1 and two is printed here so this is how we use the break to terminate the loop or exit the loop now we will learn about the continue the continue statement is used to skip the current iteration of the loop and the control flow of the program goes to the next iteration let’s see the example here if I write continue then what will happen first the I value will be one so it will not be executed then I will be two it will not be executed then I value will be three once the I value is three it will get this continuous statement when it will get the continuous statement it will skip the remaining code of this for Loop it will directly come to the next iteration it will increase the value of I by 1 so I will be for so the four will be printed now you can see the output 1 2 4 5 3 is not printed because when the I value is three it will skip this part and the I will become four then again four will be printed so this is how break and continue statement works so this was all about the for Loop while loop do while loop break and continue in this tutorial we will learn about function in JavaScript a function is a block of code that performs the specific task functions in JavaScript are reusable block of code that can be called from anywhere in your program here is the syntax to declare a function a function can be defined using the function keyword followed by the function name the body of a function is written within this curly process now let’s create a function to print a text we will use the function keyword and the function name is GRE to print any text we will add console.log and message in the double code now we need to call this function to execute the code written in this function for calling this function we will use the function name and parenthesis so simply we will add great and this parenthesis so this estate will evoke the function or call this function after that you can see the output in the console tab hello Greatest Tag is printed here so this is the function declaration using the function keyword and the function name this is the body of function where we will add the code that will be executed within the function and this code is for calling this function or evoke the function now we will learn about parameters and arguments parameters are the variable that are declared in the function definition while the arguments are the value that are passed to the function when it is called let’s see one example of function with parameters we will create one function with the function keyword and the function name is gr and in this one we will add two parameters first name comma last name so this first name and last name are variable that are declared while declaring this function this is known as parameter now we will add the code in the body of this function here we will add console.log and we will add the text hello plus there will be first name then we will add plus and one space within double quote then again we will add plus and last name so it will print hello first name and last name in the console tab so right now we have declared the function with two parameters now we have to call this function while calling this function we have to pass two values that will be arguments so to call this function we will add the function name GRE and with this function name we have to add two values so let’s add first value Elon comma musk so we are passing two values when calling this gr function now you can see the output in the console tab here it is printing hello Elon Musk let’s add a space here now it looks good hello Elon Musk is printed in this console tab we can pass any data type as argument so let’s add another data type I will add 200 that will be number here also we will add 100 now see the output you can see it is printing hello to 200 and 100 so we can pass any data type as argument while calling the function we can pass less or more arguments while calling a function if we pass less arguments then the rest of the parameters will be undefined if you pass more arguments then additional arguments will be ignored let’s see one example if I just pass GRE alone and comment this first call here you can see the output it is saying hello Elon and undefined because we are passing only one argument and here we have two parameters first name and last name so this alone will be stored in this first name so it will print hello and the first name is Elon and in the second parameter which is last name we are not passing any argument so it will be un defined that’s why it is printing hello Elon undefined the last name is undefined so we can pass less argument now let’s see another example if you pass more arguments here if I add Alon comma musk comma Mr now see the output here it is printing hello Elon Musk so the first argument will be stored in the first parameter which is first name second argument will be stored in the second parameter which is last name and this third parameter will be ignored because we have only two parameters here so it will only print this hello and the first name Elon and last name musk the third argument will be ignored now let’s learn about default parameters default parameters in JavaScript are parameters that have a default value this means that if the argument is not passed to the function the default value will be used let’s see one example of default parameters here we will create one function write the function name sum and in this sum function we will add two parameters which is X and Y now in this body of function we will add console.log and it will log the X + Y it will add the X and Y value and it will display in the console tab now to call this function we will add function name and parenthesis but here you can see we have two parameters X and Y so when calling this function we have to pass two arguments also so let’s add two values 10A 15 15 so this 10 will be stored in x 15 will be stored in y and this console. log will display 10 + 15 that will be 25 you can see in the console tab it is printing 25 10 + 15 now you can see if I remove 15 from here and we are just passing 10 10 will be stored in X and Y will be undefined and here we are printing x + y so let’s see what will be output here it is printing n n why it is because here we are adding 10 plus undefined x + y will be 10 plus undefined that’s why it is printing NN that means not a number we cannot add the undefined n number so it is printing an N here we are passing only one parameter and you want this function to work for that we can add Y is equal to 0 suppose we have added y value zero then you can see the output in the console tab it is printing 10 let’s see if I add 50 we are passing 50 in X and Y default value is zero so x + y that means 50 + 0 that will be 50 you can see the output 50 is printed so 0 is the default value of this y parameter and here if we pass two numbers 50 + 30 then it will use 30 in this y you can see the output 50 + 30 80 is printed here because we are passing two arguments 50 50 will be stored in x 30 will be stored in y so this was the default parameters in Javas script now we will learn about function return the return statement can be used to return the value when the function is called the return statement donates that the function has ended any code after return is not executed let’s see one example if I create one function and function name is ADD and in this one we will add two parameters A and B now we can add return A+ B so this function will return the addition of A and B now to call this function we will add the function name add and in this one we have to add two values as argument so we will add 10 and 20 so this will call this function and this function will return the addition of 10 + 20 so we can store this result so here let’s add one variable with the let keyword let result equal to add function so the return of this add function will be assigned in this result variable now we can print this result we will add console do log the sum is result now you can see the output in the console tab it is displaying the sum is 30 if we add 10 and 40 you can see the output in console tab the sum is 50 so this return statement will return the value if we add any code after this return a statement like a multip by B this code will not be executed return statement denotes that the function has ended any code after this return statement will not be executed in JavaScript a function can return another function Also let’s see one example here if we create one function with the function name fn1 so this is the first function here I’m adding one parameter X in this function one we will create another function let’s create function fn2 and this will accept one parameter y now in this second function we will add return X multiply y so so the function two will return the multiplication of X and Y next after this function two we will add return FN 2 so when we will call this function one it will execute this function two also and then it will return this function two so function one is returning another function that is function two to call this function we will add fn1 parenthesis and we will pass one argument so let’s add three so here we are calling function one and passing one argument let’s store its value in one variable we will add let result is equal to function one and try to print this result console DOT log result so you can see the output in the console tab here it is displaying one function so you can see when I am calling this function one it is returning the function two and that function two is stored in this result now the function two is stored in this result so we can simply call this result like this result for the second function also we need one argument so we will add two and let’s print this one we will add console.log and print this result two you can see the output it is displaying six because in function one I passing three that will be X and function two I’m passing two that will be y and x * by y will be 3 * 2 is = to 6 let’s understand this example again again here we have the function one this function one has return a statement and this return a statement is actually returning the function fn2 which is declared here so the function is returning another function now we can store the return value in any variable so here we have called and stored the return of the function one in result with this console log we can see what is stored in this result so in this result function two is a stored so to call this function two we will add result and we will pass one argument so this was another example of return a statement in JavaScript function so this was all about function in this video we will learn callbacks in JavaScript a callback is a function passed as an argument to another function a callback function can run after another function has finished let’s understand the callbacks with one example I’m creating one function and the function name is display and this display function will display the message in the console tab so here we will add console.log and let’s add result and this result is parameter so here we have declared One display function that will only display the result in the console tab we are not performing any calculation in this function now we will create another function let’s add the function keyword and the function name is add this add function will have three parameter let’s add num one then num two and the third one will be one function let’s add my call back in this add function we will add let sum is equal to num one plus num two so this sum variable will store the value of num 1 + num 2 next we will add this call back and and in this call back we will add Su now we will call this add function so just add the function name which is ADD and parenthesis and this function has three parameters so we will pass three argument so first one will be one number that we want to add again we will add another number 1020 and in the next parameter we will pass one function so we have already created this display function so we will pass this display function in this add function when you pass a function as an argument remember do not use the parenthesis we will simply add the function name there is no parenthesis required so let’s understand this code here we have declared one function that will just display one message in the console then we have another function that have three parameters s it will add the two number and store the value in some variable now to print this sum in console we need to call this display function so when calling this add function we are passing the two numbers 10 and 20 that will be added and we are passing this display function as argument and this function will be here in my callback this display function also accept one argument so here I adding my callback and the value which is sum so this my callback will call this display function so let’s see the output in the console tab you can see it is printing 30 we are calling add function and in this add function we have not added console.log the console.log is added in the another function called display and we are passing this display function as argument in the add function function let’s change the value if I write 20 + 30 and now again check the output you can see it is displaying 50 that is 20 + 30 so when we are passing one function as an argument to another function that is known as callback function in JavaScript now let’s learn about Anonymous functions Anonymous function in JavaScript are functions that are not declared with a name here is the Syntax for anonymous function just write the function keyword and parenthesis and add your code within the curly Braes we can add parameters also in Anonymous function so this is the syntax to create Anonymous function we are not adding any function name we are just adding function keyword and parenthesis and curly Braes now let’s see one example of anonymous function here we will create one function with the function keyword this function will have two parameters X and Y now this function will return the value of x + y here I’m creating one function without any name so it will not be stored on our memory so to access this function we can store this function in any variable so let’s add let keyword to create one variable and the variable name is sum sum is equal to function here we have declared one function and assigned this function in a variable called sum this is known as function expression to call this function we can use the sum variable here we will add sum and this function accept two argument so we will add the two two value in this parenthesis 10 and 15 now to print this value in the console tab we will add console.log and write this sum and two parameters now you can see the output in the console tab it is printing 25 let’s change the value here we will add 10 and 30 now again you can see the output 40 so let’s understand this example again here I’m creating one function without any name and assigning this function in variable called sum to access this function or call this function we can use this sum variable and this function accept two argument so with this sum we are passing two argument 10 and 30 this 10 will be stored in X and 30 will be stored in y so it will return the X x + y value that will be 40 that will be printed in our console tab now let’s see another example of anonymous functions here we will create one function with the function keyword and write the parenthesis and within the curly braces we will add console.log and one message welcome to greatest de here we have declared one function without any name but how to execute the code written in this function as you know to call any function we write the function name and parenthesis so this will call or execute the function we will add the same thing with this Anonymous function also we will trap this Anonymous function in a parenthesis like this we have wrapped it in this bracket and now we will add this parenthesis that will execute this function now you can see in the console tab it is printing welcome to greatest stack the function is executed immediately when the script runs and it logs the message welcome to greatest T to the console now let’s see another example of anonymous function here we will add set timeout function and time set time out is built-in method in JavaScript that accept one function and time in milliseconds so here let’s add 2,000 milliseconds and here we will create one function so here we can add one Anonymous function let’s add function keyword then parenthesis and curly Braes and in this curly Braes we can add the code that will be be executed within this function so let’s add console.log hello creest stag here I’m adding an anonymous function that display the message hello greatest tack in console and here I’m adding 2,000 milliseconds so it will execute this function after 2,000 milliseconds that is 2 seconds let’s see the output in the console tab you can see it is blank but after 2 second it display the message hello greater stack now increase the time if I add 5,000 milliseconds that will be 5 seconds and run the code again you can see the console is blank and after 5 Seconds it will print hello greatest stag you can see it is printing hello great stack in the console we can write like this so it will be clear now you can see we have declared one function without any name so this is another example of anonymous functions now we will learn about recursive functions in JavaScript a recursive function in JavaScript is a function that calls itself let’s create one function and the function name is my function and within this function we can write the code and after that we will call the same function here we will add my function and parenthesis so in this one you can see we have declared one function with the name my function and within this function we are calling the same function my function parenthesis now to evoke this function we will add it here outside of this function here my function is recursive function because it is calling itself inside the function a de cursive function must have a condition to stop calling itself otherwise the function will be calling itself infinitely to prevent infinite recursion we can use if else statement or any condition statement so here if I add if if condition and within this condition we will call this recursive function and else stop calling recursion so this is just one example how we can create one recursive function and call the recursive function and how to prevent the recursive function for infinite recursion we can add the if Els condition or any other conditional statements of JavaScript now let’s see one example I want to print numbers in descending order so here we will create one function and let’s add the function name countdown so this countown function will accept one number so here we will add num to call this function we will add the function name countdown and we will pass any number let’s add 10 so this will call this countdown function and pass the number 10 in this num now to print this number we will add console.log num so this will will be printed in the console tab now I want to print 10 9 8 7 like this so we have to decrease the number so after printing the number in console we will decrease its value by one so simply we can add num minus minus so it will decrease the value by 1 if the number is 10 it will become 9 so after decreasing the number again we have to print it so to print the number again we can call this function again let’s add countdown num so this countdown num will again a start from here and it will again print this but this countdown will be running infinitely so to prevent the infinite recursion here we will add if num is greater or equal to Z so when the number is greater or equal to Z then only it will call the function again now you can see the output it is printing 10 987 65 4 3 2 1 0 it is printing the number from 10 to 0 Let’s understand this code again here we have declared one function and in this function it is printing the number and it will decrease the number by one and after that it will check if the number is greater or equal to zero then it will call this function again so this countdown function is calling itself this is known as recursive function so this is all about recursive function callback function and Anonymous functions in JavaScript object in JavaScript JavaScript object is a non-primitive data type that allows you to store multiple collections of data let’s see the syntax to declared an object we will use const keyword then object name so this is an object in this we can add the data in key value paired we will add key 1 value one we will add the comma to separate the data we will add another key key2 and value two we can use the let keyword also to declare one object but it is good practice to use the const keyword let’s see one example if I write the object name person and in this person object we will add the name of the person so first we will add first name and in the first name we will add Elon add one comma then we will add the last name the value is musk and we will add one more information age so here we have created one object with the object name person in this object we have three properties now let’s check the type of this person we will add console.log type of person now you can see in the console tab it is printing object so the type of the person is an object now if we want to print the complete object we will add console.log person in this console you can see it is printing the object that we have created it is printing age 35 first name and last name any object can store two things which is properties and methods in this person object data is stored in key value pairs first name is the key Elon is the value age is key 35 is value these key value pairs are called properties key is always stored as a string here if I write this name in double quote still it will be correct you can see there is no error in the output you can see it is displaying simply first name so by default it will store it as a string in the value we can add any data type we can add a string number arrays Boolean function and we can store an object also when we declare a function as has a value in key value pair then it is known as methods now let’s learn how to access the properties of an object we can access the values of a property by using its key name so the first way of accessing the property is using dot notation we can write object name dot key so it will give the value stored in the key value pair of the object let’s access the value stored in this person object here we have the console.log person and if you want to access the name stored in the first name so we will add person. first name and we will check the console you can see it is printing Elon so we can access the property using dot notation let’s add the age here if you want to access the age object name and key so it is displaying the value in the console you can see it is printing 35 the second way of accessing the properties of an object is using bracket notation so in this example here we will remove this Dot and add a square bracket and we will add this text in double quote as a string now you can see the console tab it is printing 35 so we we can access the property by using braet notation and in this braet we have to add the key name with double quote or single quote let’s add the first name so you can see the first name in the console Alon keys in object are stored as a string so we can add this key in double code like this and we can add a space Also here we are adding first space name like this now if you want to access the value stored in the first name we will add console.log and object name and if you use dot here DOT first name it will give an error we cannot access this property by using do notation in this case we have to use the bracket notation only and in this bracket notation will add the string in double code or single code then you can see it will display the name it is displaying the name alone in the console tab so the bracket notation is also useful to access the properties of an object now let’s see how to update the properties of an object so we have this object person and in this one if I want to update the first name so the first name is Elon and I want to change it so we can add the object name that is person and write the key that will be first name and we can assign a new value or a new data so here we will add Mr Elon Mr Elon so this line will update the first name in the object called person now you can see the output it is displaying Mr Elon because here we are printing person. first name here we have declared one object with the person and here the first name is Elon and in this line we are updating the first name with the new name which is Mr Elon and Mr Elon is printed using this console.log next we will learn how to add a new properties in the object so here we have the object with three properties and now I want to add one more property so for that we will add the object name so the object name is person then we will add the key so key is company so this line will add a new property in the person object now if you want to display the object just add console.log and object name now you can see the console tab it is displaying the object with four properties age company first name last name so we have added one new property company and it is displaying in this object next we will learn how to delete one property from the object so let’s use the same example and here we will add the delete keyword delete then write the object name and key so let’s delete the age that’s it we are adding delete keyword then object name and key now if you want to check let’s see the console tab here you can see it is displaying only three property which is company first name and last name age property is missing because we have deleted age property from this object this is how you can access the properties of an object you can update the property you can delete the property and you can add a new property as I have already discussed in value we can store any type of data so we can store one object also that is nested object so let’s take the same example in this one we will add one more property here we will add address and this address will contain another object that’s it we will add the data in key value pair in this example you can see we have an object called person and in this object we have three properties then we have added one more properties and this property is having one another object that is known as nested object and in this object also we have added the data in key value pairs you can see Street city state country and zip code now to access the data stored in the nested object we can use the same dot notation let’s add console.log write the first object name person and in this object we have the address we will add address and from the address we can access CT now you can see the console tab it is printing Austin now if you want to access ZIP code right person address ZIP code now you can see it is displaying zip code in this console so so this is how you can access the properties of the nested object now we will learn how to check if a property exist in an object to check if a property exist in an object you can use the in operator we can write property name in object name here we have the person object so let’s see one example to check if the property exist in this person we will add age in person it returns true if the property exist in the object so let’s print this in console tab we will add console.log we have to add this age in quotes now you can see in the console it is printing true because age exist in this person now if you want to check first name is exist or not so here we will add first name in person so it will display true because we have the first name in the person object now if you will add country country in person now you can see it is displaying false because in this person object we don’t have any property with the key name country now if you want to display all properties and values of an object without knowing the property name then you can use foreign Loop foreign Loop allows you to access each property and value of an object without knowing the specific name of the property for example we will add for and in this one we will add one variable so let’s declare one variable with the let keyw word and we’ll add the variable name prop that is properties and prop in object name person now we can print this prop so let’s add console.log prop in the console you can see it is printing first name last name and age because in this person object we have three keys first name last name and age so using the for in Loop you can access all properties of an object now if you want to access the values stored in this key we can use the bracket notation as we have already discussed to access the value we use the object name like person and bracket notation and in this one we will add the key so let’s add H so it will display the value so here we will add the same thing let’s add person Square bracket and prop so you can see the output in console tab it is displaying the values only the values are Elon Musk and 35 now if you want to display both key and value so let’s add prop plus and here we will add colum now you can see the output in the console tab it is displaying both key and values stored in this person first name Elon last name musk is 35 so using the for in Loop you can access all the properties of an object there are multiple ways to create an object in JavaScript this was the example to create an object with object literal let’s see another example where we will create an object with the new keyword for that we will add const [Music] person new object so this is the another way to create an object if you want to add some data in this object we can add the object name and key and assign one value so it will add this data in this person object let’s duplicate it and we will add another data last name age now if you want to display this person object just add console.log person you can see in the console tab it is displaying one object with the data Age first name last name so you can see we have created one object with the new keyword and then we have added these data in this person object we can add these data while creating an object Also let’s see I will remove these things remove it from here and in this object just add curly Braes and within this curly Braes write the data in key value pair and here it will be comma now it will create the same thing you can see the output it is same still it is displaying the object with three properties first name last name and AG so this was all about JavaScript object and their properties in this video we will learn about JavaScript object methods JavaScript method is an object property that contains a function definition let’s create one object with the const keyword here we will add the object name person and in this object we will add two properties first name and last name let me create one more property here and I will add the property name GD you can call it property name or key in this gr property we will declare one function to declare a function we use function keyword then name of the function so let me write the function name g and in this function we will print one message using the console log hello world so in this one you can see we have the third property with the function definition this is called as object methods so this is the method of the person object now to call this method we will add the object name that is person and then write the method name GRE and write the parenthesis also now you can see the console tab it will display the output hello world so in the person object we have created one property with the function definition that is known as method and we are calling this method using the object name do method method name parenthesis here we have declared one regular function we can add the anonymous function Also let’s remove this name and we can write like this here we have used function expression to define a function and assign it to the GD property of the person object and still it will display the same message in the console tab hello world we can declare a function outside of the object and assign it to an object as a method here is one example let me remove this function from here and here we have one object with two properties now we will declare one function function name is grd and console.log hello world next we will assign this function inside this person object so here we will add person dot any key name so we will add the key name greeting is equal to greet let me add T it will be correct so in this line I’m assigning this greet in this person greeting now to display the output we will add the person dot greeting parenthesis now you can see the output it is displaying hello world so let’s understand this example again here we have created one object and the object name is person where we have only two properties now we have declared one function and assigning this greet function in this person object the property name or key name is greeting we are calling this method using person. greeting parenthesis now if you want to display this person object simply we will add console.log person now in the console tab you can see it will display the object and in this object you can see we have the first name then this greeting property which is the method in this greeting we have the function definition so this is how you can assign one function inside an object as a method es6 provides us one more way to declare a method for an object let me remove it and in this object we can simply add gr and curly Braes and write the code so this is one more way to declare one function in inside the object as a method we can access this method using the person dot GRE now you can see it will display the message hello world in the console tab now we will learn about JavaScript this keyword to access the other properties of an object within a method of the same object we can use this ke key word let’s see the same example one object with the name person and we have two properties first name and last name now to access the first name we use to write object name do the key name or first name so this is how you can access the property of an object but when we need to access the first name within the method so in this one let’s create one method here we will add one method G one Anonymous function and message console.log hello now in this method if I want to display the first name so here we will add plus this DOT first name so when we need to access the property of an object outside of the object we use the object name and key so we are adding person do first name but here we are accessing the first name inside this method and this method is in this person object so this keyword refers to the same object which is person so we don’t need to write the object name we can simply write this keyword do first name so this will print hello and the first name now to call this method we will add the object name Person dot gr let’s see the output in the console tab it is printing hello Elon let me add a space here now you can see it is printing hello Elon in the console tab so we can use this keyword to access the properties of the same object within the method so when we use this keyword within a method it refers to the same object now let’s define a method that Returns the full name of the person object by containing its first name and last name so remove it and let’s remove this method also and here we will add another method get full name one function and in this function we will add return this function will return the first name and last name to access the property we will add this DOT first name then we will add space so let’s add double quote then Plus this do last name it will access the last name so in this method you can see it is returning this do first name so it will return this value Elon and here this do last name it will return this value musk now to call this method we will add person dot get full name this method is returning some value so we can print it using console.log let’s add console.log person. get full name now you can see the output in the console tab it is printing Elon Musk so it is returning the full name by containing first name and last name let’s understand this example again here we have an object with the name Person where we have two properties first name and last name and one method this method Returns the first name and last name of the person now we are calling this method so it will display the full name which is Elon Musk we can use this keyword outside of the method also but it will refer to the other object let’s remove all these things and here simply add console.log this so here you can see the output it is display Ling window object so if we use this keyword alone or inside a function then it will refer to the global object that is window object or when we use this keyword in the event then it will refer to the element that receive the event this keyword is not a variable so we cannot change the value of this so this is all about JavaScript method and this keyword in this tutorial you will learn about JavaScript Constructor function and and how to use the new keyword to create an object in JavaScript Constructor function is used to create objects let me create an object we will add the const keyword then object name person and in this object we will add properties so the first property is first name and the second property last name this example create a person object with two properties first name and last name but this syntax is used when you have to create single object in programming you often need to create many similar objects like person to do that you can use a Constructor function let me create one Constructor function for that we will add function keyword and then the name of the function person then parenthesis and in this curly braces we will add properties so let’s add this DOT first name and value Elon again this Dot last name and value Constructor function is similar as a regular function but it is good practice to capitalize the first letter of the Constructor function so you can see here I have added capital P in this person a Constructor function should be called only with the new operator we can use the new operator to create an object from a Constructor function till now we have not created any object we have just created one Constructor function to create a new object we use the new operator so let’s see how to create an object using this Constructor function let’s add the con keyword then we can write any name of the object so let’s add the person one this is the object name here let’s add new operator and write the function name person so this line will create one new object that is person one using the Constructor function we can create multiple objects so let’s add one more line here we will add person two so here we are creating another object with the name Person two with this person Constructor function now if you want to see what is stored in the person one console.log person one and see the output in the console tab so you can see the person one is one object with the two properties first name and last name now let’s see the second object also so we will add console.log person two so we are printing both person one and person two in the console so let’s see the output here you can see both output is same when a new object is created using the Constructor function this keyword will refer to the newly created object so in this example here we are creating one new object person one with the new operator and this Constructor function so this keyword will refer to the newly created object which is person one and this first name and last name will be added in this person one as a property so in this example person one and person two object have same property value but we can create multiple object of the same type with different property value also using Constructor function parameters so as you know the parameters in the function here we will add parameters in this Constructor function also so in this function let’s add first last in this Constructor function we are adding two parameters first and last and this first will be stored in this first name this last will be stored in this last name now when calling this Constructor function we have to pass two arguments here we are creating object by calling this Constructor function so to call this Constructor function we have to pass two arguments so let’s pass two value Alon musk for creating this person to object we will pass another argument let’s add another name billgates so in this example here we have one Constructor function with two parameters so to call this Constructor function we have to pass two arguments so this Elon will be here in this first and this first will be stored as a value in this first name property this mask will go here in the last and this last will be stored as the value in this last name property so when we are creating person one it will create one object with the property first name and last name and the value is Elon Musk and when we’ll create the person two object it will also create the object but the value will be different that will be buil gets now let’s see the person one and person two object in the console tab so you can see the output here in this console so in the first object you can see first name Elon last name musk and in the second object we have first name will last name gets so using the Constructor function we can create multiple object of the same type now let’s see how to add properties and methods in an objects so first let’s add one property in person one object so removing this console and here I will add person one to add a new property in this person one just add Dot and the property name age and write the value let’s add 52 now we can print this in the console let’s add console.log person one you can see in the console tab here we have three properties in this person one object which is first name last name and age and the age value is 52 that we have added here person 1. AG is equal to 52 now if I simply want to print the age here we will add console.log person one do age so you can see the console tab it is only printing the value stored in this age property that is 52 now if I try to access the age from the person two let’s see what will happen here I’m adding person to. age and see the output in the console tab it is displaying undefined because we have added this age property only in the person one object we have not added in the person two object that’s why person 2.as will display undefined now let’s see how to add one method in the person two so let’s scroll and here we will add person two dot method name we will add gr and declare one function as we have already studied method is a function decaration inside the object property so here in this person two object we are adding one method with the name gr and declaring one function and let’s say this function will log one message hello great stack we have to write it in codes so we have added one method in the person two object now let’s access this method here we will add person 2 dot GD from person 2 we are calling this GRE method now let’s see the output in the console tab it is printing hello great stack in the console tab so this is the example to add a method in the object now let me remove this and you can see in this Constructor function I have added added only two properties now let’s see how to add one method in the Constructor function so here let’s add one comma and here we will add this dot name of the method get full name and here we will declare one function so this method will return some value so return this DOT first name then we will return the last name Also let’s add one space plus and this do last name so here I’m adding get full name and this method will return first name plus last name that will return the full name name so we have just created The Constructor function now we have to create object also so let me add the same example again I will add person one and person two so we have created person one and person two object using the new operator and Constructor function now let’s see how to access the get full name method so to access the full name just we will add person 1 dot get full name the method name now this method is returning some value so we can print it using log console.log person 1.g full name now you can see the output in the console tab it is printing Elon Musk now let’s access the person two full name and you can see the output billgates the problem with this Constructor function is is that when we create new object using this Constructor function the same method will be created in all the objects created using this Constructor function which is not memory efficient to resolve this we can use the Prototype of the object so that all objects created from this person Constructor function will share this same method so this is all about JavaScript Constructor function in this tutorial you will learn about JavaScript object prototype in JavaScript every function and object has its own property called prototype let’s create one object const person and this person will have name Elon so this is one simple object with only one property that is name but this person object has one more property called prototype let’s see this person object in the console we will add console.log person and you can see in the console tab here it is displaying one object name Elon right but if I expand it you can see the property name Elon but here we have one more property called prototype and the Prototype is also an object a prototype itself is also another object so the Prototype has its own prototype let’s expand this prototype again and expand any of this you can see here again we have the Prototype let’s expand another one here also we have prototype so the Prototype has its own prototype this create a prototype chain now let’s learn prototype inheritance we can use the prototype to add properties and methods to a Constructor function and objects inherit the properties and methods from a prototype let’s see the previous example of Constructor function so this is one Constructor function with two parameters and the two properties first name and last name now previously we were adding like person one that is one object and in this object we can add new property like this person. AG so it will add a new property in the person one object but here we want to add one property in the Constructor function like we have the person Constructor function so we cannot add one property like this in the Constructor function and we cannot add a method in the Constructor function like this after Declaration of the Constructor function we cannot add the extra Properties or method like this to add the another property or method in the Constructor function after declaring we can use the Prototype here we have only two property in this Constructor function so let’s add one more property so to add one property in this Constructor function we will add the function name person then prototype like this and in this prototype we will add one new property name so let’s add the property name gender and the value is male so using this we can add one new property in the person Constructor function now let me create object also so I will use the const keyword and object name so the object name is person one and create an object using new operator and the function name and pass two values and we will create one more object so duplicate this it will be person two and different value so we have two object person one and person two now let’s see whether the newly added property is available in the person one and person two or not so let’s add console.log person one object and and see the output in the console tab here it is displaying first name Elon last name musk here we have only two properties but we have added the another one gender which is not available here but if I expand it and come to the Prototype here we have the Prototype and open this prototype here you can see our newly added property gender male in this prototype so you can see how you can add a new property in the protot prototype and this prototype property will be inherited by all the object now let’s see the output for the person one. GN Zender and see the output it is displaying male because the object is inheriting the properties of the Prototype now let’s see the output when we access the person two for the second person object let’s access the Ender and you can see it is displaying name male again here we have added gender property in the person Constructor function using prototype and this person one and person two objects inherit the gender property from The Constructor function prototype gender property is not available in the person one and person two object you can see in the console but still we can access it because it is added in the Prototype which is here now let’s see how to add one method in the Constructor function so here we have added one gender property so instead of this we will add one method let’s add method with the name get full name and this method will be a function definition so in this function we will return the full name so write return this DOT first name and space this dot last name so in this person Constructor function we are adding one method using the Prototype and this method name is get full name this method will return the first name and last name of the person so let’s see the output of the person one in the console tab you can see it is displaying first name and last name in this console but if I expand it here you can see we have the Prototype and if I expand this prototype you can see in the person one prototype it is displaying get full name method you can see the get full name method is here so this get full name method is not added in this person one or person two this person one and person two object is inheriting this method from the Prototype of the Constructor function so we can access it like this get full name person 1.g full name let’s see the output it is printing Elon Musk now we can access this get full name from the person two also and see the output it is displaying billgates let’s understand this example again here we have created one Constructor function with only two properties after Declaration of the Constructor function we cannot directly add new property or method in this function but to add the new property or method we will use the Prototype so we are adding person. prototype and the method name method is a function declaration so we are adding function and this function will return the first name and last name now here we are creating two objects with the Constructor function person one and person two now this person one and person two does not have the get full name but still we can access the get full name method from person one and person two because it is inheriting the Prototype of the Constructor function so we can access person 2.get full name and we can also access person 1.g full name now let’s see what will happen if I change the Prototype value so let’s create one Constructor function here we will add one property Elon mask and in this one we will add one new property using prototype so we will add person do prototype and the new property name age is equal to 25 so we have added one new property in the Prototype that is age is equal to 25 now we will create one object so to create an object we will use the const keyword and the object name it is person one and new then Constructor function so this will create one new object that is person one so here we have created one new object called person one after creating this object let’s change the value of this property so in the next line we will add person do prototype is equal to age 52 like this earlier we have added age 25 and here we are changing the Prototype property age 52 so after changing again we are creating one new object const person two new and Constructor function so before changing the property we have created one person one object and after changing the Prototype we have created person two object now let’s see the output in the console tab so we will add log person one and person two and you can see it in the console tab it is displaying name Elon Musk in both object but if I try to access age and age in the second object so you can see the output for the person one it is displaying is 25 and for person two it is displaying is 52 because if a prototype value is changed then all the new objects will have the change property value and all the previously created objects will have the previous value so in this example you can see here we have the property value 25 and created one object person one in this person one object A’s value will be 25 and before creating person two we have changed the property so this person two will have the updated property value that will be 52 that’s why it is printing 25 for the person one age and 52 for the person 2 Age so this this was all about JavaScript prototype in this tutorial you will learn about object destructuring object D structuring in JavaScript is a feature that allows you to extract the properties of an object into variables this can be useful for assigning the properties of an object to variables in single statement let’s understand it with one example we will add one object with the name person here we have created one person object with two properties first name and last name to aore these properties value in a variable we used to write person DOT first name this is for accessing the first name of this person and to it in variable we used to write let and one variable name like f name is equal to person. first name like this if I want to store the last name we will add another variable name L name Person dot last name so this is the previous syntax to store the object properties value in a variable but es6 introduces the object D structuring syntax that provides an alternative way to assign properties to an object variables here is the Syntax for object D structuring we will add L and in this curly Braes we will add property name and value another property name and value and here we will add the object name that’s it so let’s assign the properties of this person object in variables using the object D structuring here we will add person and here we will add the property name so the property name is first name and this first name will be stored in the variable called f name now add one comma and write the another property name and for this property name again we need one variable so the variable name is last name so this is the simple syntax of DS structuring we can write the property name and value to store the object properties value in variables now if I check the value stored in this F name variable or L name variable we will just add log F name you can see it is displaying alone if I I add L name here will be capital n and you can see the output musk we can further simplify this syntax suppose you want to add the variable name same as the object’s property name like object property name is first name and last name and our variable name is also first name and last name then here we don’t have to write the variable name just write first name and last name and then object now to print this we will add console.log first name it is printed here in this console now let’s add last name you can see the last name in this console so this is the simple syntax of object destructuring here in this object we have only two properties but what will happen if I add one more property in this object destructuring syntax let’s add one age that is not available in this person object then what will happen let’s see the output if I add console.log age it is printing undefined because this age property is not available in this person so when you assign a property that does not exist in an object to a variable using the object D structuring the variable is set to undefined now in this object D structuring we can add the default values also suppose here we don’t have the age value so we can add like this age is equal to 18 so this is the default value of the age variable if the property is available in this object it will display the actual value and if it is not available it will display this default value 18 so you can see the output it is displaying 18 because the default value for the age is 18 now suppose this age is available here in this object we are adding age 52 now what will be the output you can see the output it is displaying 52 because it will ignore the default value here we already have age declared in the person object so this age variable will store the actual value of the property which is 52 so this is all about object D structuring now let’s learn about object literal syntax extensions in es6 to create one object we used to write like this const person and first name and last name so this is the object literal syntax to create an object with the key value pairs but here if I typ one variable let first name equal to Elon and last name m here we have two variables first name last name so we can simply add first name comma last name we don’t have to write the key values in this object we will simply add the variable name and this person will store this information as key value pair now if you try to print this person let’s add console.log person you can see it is displaying first name Elon last name musk so we are just adding the variable name in this person object and this person will store the variable name and value also as a key value pair so this is all about objects in JavaScript in this video we will learn about JavaScript class classes are one of the feature introduced in es6 version of JavaScript JavaScript class is a template for creating objects to create a class we use class keyword then we write the name of the class within the class we create one Constructor method you should always add a method with the name Constructor within the class the first letter of the class name should be in capital letter JavaScript class is similar to the JavaScript Constructor function to create a Constructor function in JavaScript we use to write function and name of the function I’m adding person in this function we will add here we will add the code to initialize the property value of an object after creating the Constructor function we create object we can write any object name person one new keyword and Constructor function and pass two values here so this is for creating one new object to display the object created using this Constructor function we used to write console.log person one you can see the output in this console tab it is displaying one object with the property name and age now we can create the object using class also so now let’s create the class to create a class we use to write class keyword then class name I’m adding the class name person and in this class name we have to add one Constructor method and this Constructor method is used to initialize the value of the object so let me add this here here we will add two parameters so this is one class with the name person and this line will create one object with this class now let’s duplicate it we’ll create another object with the name Person two and we will pass another value so we have two objects person one and person two now if you want to display the object in console tab you can write console.log and you can see the output it is displaying here one object with two properties name and age and the name is Elon Musk and age is 52 now let’s print second object which is person two you can see the output in the console tab it is displaying another object object with the name billgates and age 67 this Constructor method initialize the property of the object JavaScript automatically calls the Constructor method when you create an object using the class now let’s learn about JavaScript class methods we can add any number of methods in JavaScript class so let me remove this second person and in this class after this Constructor we can add any method so let’s add one method with the name greet and this greet method will return text hello this do name it will return hello and name of the person now I want to display this person one object so here I will add console.log person one and in the console tab you can see one object with two properties name Elon mask is 52 now let’s expand it and here you can see prototype and in this prototype you can see this GRE method in this prototype of the object so we can call this GRE method from this person one object so in this console.log I will add G and you can see the output it is displaying hello Elon Musk because we are calling the Greet method from the object and this greet method is returning the text hello and the name so that’s why it is displaying hello Elon Musk we can add any number of methods so let’s add another method here here I will add a new method change name this change name method will update the name of the person in the object so here we will add new name and then this do name is equal to new name so in this method we are adding one parameter so when we will call this method we have to pass one argument let me remove this console.log and here I will call the change name method on person one object so just add person one dot change name and we have to pass one argument so let’s add a new name I will add my name here AAS now we can print the object let’s add console.log person one you can see one object name aenas age 52 now if you want to print the name only here we will add person 1. name it is printing the name in the console tab so in the JavaScript class you can add any number of method now let’s learn about gets and Setters in JavaScript Getters and Setters are a special methods in JavaScript that allow you to control how properties are accessed and modified they are defined using G and set keyword now let’s understand the getter method a getter is a method that is called when a property is accessed it can be used to do things like validate the value of property or convert it into different format so let’s see this example here we have one class with only one method great and this method is returning hello and the name here we have created one object using this class this code will call the Greet method from the person one object and display the return value in the console so while calling this great method we used to write this parenthesis but when we clear it as a geted method so here we will add get space and the method name that’s it just add the get keyword and after that here you don’t need to write the parenthesis simply add gr person one. greet and save the changes you can see the output it is still displaying the message hello Elon Musk so we have just added this get keyword in front of this method name and we can call it directly without adding parenthesis now let’s understand the seter method with one example here we will change the method I will add change name new name this do name is equal to new name to call this method we need to write person one dot change name and pass one argument like this but here we will add set keyword in front of this method just add set then we don’t need to write this parenthesis and pass the argument simply we will add person one do Setter method name and assign one value using assignment operator like this and see the output here I’m displaying the person one object it is displaying one object and name is AAS age 52 like this so we add this set keyword to Define one Setter method we can call this method on object and assign one value with assignment operator a Setter is a method that is called when a property is modified it can be used to do things like update the value of the property or perform some other action we can use the same method as getter and Setter let’s see one example let me change the method name it will be person name name and here I’m adding set now we will add get this will be getter method and I’m adding the method name same as the setter method here also person name and this will return return this dot name so you can see here we have declared one class in this class we have one Setter method and one getter method and both method name is same person name and person name now to call this getter method we’ll simply add console.log person one do person name so it will return the name of the person you can see the output it is displaying the name now we can update the name using this Setter method so let’s add person one dot person name and just assign one value after that again we will call this get method that will displ play the name so you can see the output first it is displaying the name Elon and after that it is displaying the name ainash so we have the same method name as getter and Setter to call the getter method we are simply adding the object name and Method name and to call this Setter method we are adding object name and Method name and assigning one value that’s it when we assign any value it will call the setter method and update the properties value let’s learn about JavaScript class expression a class expression provides you an alternative way to define a new class it is similar to a function expression but it uses the class keyword instead of the function keyword class expression can be named or unnamed if they are named the name can be used to refer the class later if they are unnamed they can only be referred by the variable that they are assigned to so let’s define one class expression we will add the class keyword in this class we will declare one Constructor method this Constructor method will initialize the object property property name is name here we will add name and in this class we will add one method method name is get name it will return the name now we will assign this class in a variable let’s add let keyword person is equal to class A Class expression does not require an identifier after the class keyword you can use a class expression in a variable declaration now we can create an object so let’s add cost person one new person we can refer this class with this variable and here we will add one [Applause] argument now we can display our object in the console tab so let’s add console.log person one you can see the output in this console here we have one object with the name Elon Musk so this was the class expression in JavaScript in this video we will learn about JavaScript class inheritance JavaScript class inheritance allows you to create a new class on the basis of already existing class using class inheritance a class can inherit all the methods and properties of another class inheritance is a useful feature that allows the code reusability to create a class inheritance we use the extend keyword so let’s create one class write the class name Person add one Constructor method and add one method GRE console.log hello and name here I have created one class now I will create another class that will inherit all the methods of the person class so here we will create another class and the class name is a student then write the extends it will extend person so we are creating another class with the name a student this a student class will inherit all the method and properties from this person class in this new class we have not added anything but let’s create one object here we will add con student one this is the object name is equal to new student and we have to pass one value Peter so we have created one object with the name a student one and we are passing one value in this student but this student don’t have the Constructor and here we have added extends keyword so it will inherit all the method of this person class and it will pass this page Peter here in this Constructor and the name will become Peter and we can also call this greet method so let’s try to call this greet method we’ll add a student one do greet you can see the output it is displaying hello Peter so this property name is available in this person class this method is also available in this person class but we are creating the object object with the a student class and calling this method from the object of a student class so we can call the method and properties of the parent class it means a student class is inheriting all the method and properties of the person class now let’s learn about JavaScript super method the super method used inside a child class donates its pent class in this student class let me create one Constructor add one parameter and in this Constructor we will call Super here this super method inside the student class refers to the person class when we create one object using the student class it will call this Constructor method automatically then it will call this super and then the super will call this Constructor from the parent class which is person class and pass this name here in this Constructor then the argument will be stored in the person’s name still it will display the same output you can see in the console hello Peter let’s understand this example again here we have created one person class and we have another class with the name student and this student class class inherits the property of the person class so this is the parent class this is child class in this child class I’m adding super so this super refers to the parent class which is person class and it will pass this argument in the pent class so this was the Super method in JavaScript now let’s understand what is Method or property overwriting or ping method suppose the parent class and child class has the same method or property name in this case when we call the method or property of an object of the child class it will override the method or property of the parent class this is known as method overriding or cying method let’s understand the method overriding with one example here we have the parent class and this is the child class in this one let’s create the same method greet and in this greet method we will add console.log hello student plus this dot name and in this one we will add hello person this do name so you can see in this parent class and child class we have the same method name which is GRE in the parent GRE it prints hello person and name and in child class this greet method prints hello student and name now if we call the Greet method from the object created using child class then it will call the method of the child class you you can see the output in the console tab it is displaying hello student Peter it means it is calling this greet method from the child class so the method of the child class override the method of the parent class this is known as method overriding now let’s learn about JavaScript static methods static methods are bound to a class not to the instance of the class you cannot call the static method on an object it can be called only on the class so let’s declare one class class name is person and in this one let’s declare one method this method will display only text hello on the console now in front of this method if I add static it will become the static method now we cannot call this greet method on the object created using the person class we can call this greet method only on the person class let me make it capital P here the name of the class should just start with capital letter now let’s create one object here we will add const person one is equal to new person Peter and if I try to access the GRE method from the object object name is person one dot GRE it will display one error you can see the console tab it is giving an error now if I add person. greet I’m adding the class name and greet you can see the output here it is displaying hello now if you want to use these object properties inside this static method then you can pass the object as a parameter so let’s take another example here we have the person class then we have the St method in this a static method we will add one parameter X and in this console.log I will add hello space X do name so it will display the name from the object now we can call this greet method from the person class and we have to pass the object let’s pass this person one object here and now you can see the output it is displaying hello Peter because here I’m adding hello then object then property name so from this person object it will get the property name name is equal to name so the name will be Peter and here I’m adding text hello so hello Peter is printed in this console so this is the static method in the JavaScript now we will learn about JavaScript private methods private methods are accessible only within the class it means we cannot call the private methods outside of the Class by default methods of a class are public to make a method private we need to start the method name with the hash tag so let’s take one example I will add class person Constructor first name and last name we have two parameters this DOT first name will be first name then this do last name it will be last name now let’s create one method in this class method name is full name and it will return this DOT first name then a space this do last name so it will return the full name now let’s create one object using this person class I will add const person one is equal to new person and here we have to pass two argument Peter and let’s add anything B so we have created one object with the name person one now let’s see if I add person one dot full name we can call this method right and it is returning one value so we can add console.log person. full name you can see the console tab it is displaying Peter V it is returning the full name now if I add hashtag here so this method will become private method now we cannot access this private method outside of this class you can see the output it is giving an error now let’s see how to access this private method inside the class so in this class only we will create another method let’s create one method called display here we have display method and within this display method I will add console.log and here we can call this method but to call this method we have to add this this dot full name this will refer to the object and this is the private method with the hashtag now we can call this display method outside of the class so simply add person one 1. display and it will display the output here in this console tab it is displaying Peter B so let’s understand this example again here we have declared one class with the name person in this one we have this Constructor that will initialize the object properties then we have this private method and this method name I have added has tag that’s why it becomes private method now we cannot call this private method outside of the class we can call this method inside of this class so within this class we are calling this method here and to call this method within the class we need to add this keyword this dot method name with the hashtag so like this we can call the private method within the class now let’s learn about private static method this is the private method now we can can add the static keyword like this so it will become private static method and we cannot call the static method on the object we can call the static method only on the class so here we have to pass one object while calling this method so here we are calling this method so in this one we will pass the object so we will refer the object with this keyword we will pass the object and here we will add one parameter and from this parameter it will get the first name and last name it means it will get the first name and last name from the object that we are passing through this keyword while calling this private static method now you know we cannot call this a static method on the object we can call it on the class so instead of this keyword we will add class name person person dot has full name now you can see the output it is displaying Peter B let’s understand this example again here we have declared one class in this class we have one static private method now to call this a static private method we will use the class name dot method name with the hashtag and to get the object’s properties we are passing the object as argument here we are calling display method from the object this display method will call this class and this static method that is a static and private method so we can access the estatic private method using the class name person now we have completed class in JavaScript now we will learn about document object model the document object model is an API for manipulating HTML documents the Dom provide functions that allow you to add remove and modify part of the document effectively the Dom represents an HTML document as a tree of nodes in this HTML code you can see this is the node this HTML tag is a node this head tag is also one node this title tag is a node this text Greatest Tag is also one node this body tag is a node this comment is a node and this P tag is also a node now let’s understand about the node type so this one is the document type node these HTML head title body these are the element type node and these text are the text node and this is the comment node now let’s learn about node relationship any node has relationship to another nodes in the Dom tree and it is same as described in the traditional family tree for example this body is the child node of this HTML node and this HTML node is the parent node of this body node this body node is the sibling of this head node because they share the same immediate pent which is HTML element now let’s add some other content within this body here we will add one div and add this P tag within this div let’s duplicate this so we have four P tag in this div so this div element is the pent node of these P tag and the P tag is the child node of this div this one is the first child and this one is the last child the second p is the next sibling of the first one this third p is the next sibling of the second one and the fourth one is the next sibling of the third one in same way you can say the first one is the previous sibling of this second P the second p is the previous sibling of third p and the third p is the previous sibling of fourth p now let’s learn about selecting elements using Dom to get elements in JavaScript there are various method in Dom so the first one is get element by ID method get element by ID method returns an element object that represents an HTML element the get element by ID is only available on the document object let’s understand this with one example here I will remove this comment and I will add only one text in P tag and for this P let’s add one ID so I am adding the ID message and in this P we have the text JavaScript Dom now let’s add the JavaScript in this HTML page using the script tag within this script tag we can add our JavaScript code here we will add one variable with the name MSG which is message and we can write document dot get elementy ID and here we have to add the ID of this element which is message so this document. get element by ID will select this element and it will be stored in this message variable now we can print it let’s add console.log MSG here you can see the output in console tab P ID message JavaScript Dom so this element is printed in this console because I’m adding console.log MSG so in this MSG variable we have stored this element which is in the P tag if the document has no element with the specified ID then it will return null Suppose there is no element with this ID on the web page then it will return null you can see null and if there is multiple element with the same ID it will return only first element let’s duplicate it and in this one we will only write JavaScript now you can see the output in console it is still printing ID message JavaScript Dom so it will select the first element with this message ID because the ID of element is unique with the HML document the document. getet element by ID is a quick way to access an element now we will learn about get Elements by name method every element on HTML document may have a name attribute multiple HTML elements can share the same value of the name attribute let’s take one example here we will create one input field and in this input field I will add the type radio and we will add one name attribute name will be language and value will be JavaScript we can add another input field with the same name attribute and value will be something else python in this HTML code you can see we have two elements with the name attribute and we can select this element using this name so in this sub script we will add let BTN is equal to document do get Elements by name and in this one we will add language because the the name value is language now we can print this let’s add console.log BTN and you can see the output in the console tab here we have the node list that contains two input field you can see input and input so get Elements by name returns one list of nodes now we will learn about get Elements by tag name the get Elements by tag name method accepts a tag name and return a live HTML collection of elements so let’s understand it with one example in this HTML we will add one title in H1 so the text is first heading let’s duplicate it this is second this is third this is fourth we have four text here in the heading tag now we can select the element using the tag name which is H1 so here in this sub script we will add one variable with the name heading is equal to document dot get Elements by tag name and here we will add the tag name which is H1 now we will print it using console log heading so you can see the output on the console tab it is returning the collection of four HTML elements you can see H1 H1 H1 four times so this get Elements by tag name return the collection of HTML elements now we will learn about get Elements by class name the get Elements by class name method returns an aray like of object of the child elements with a specified class name the get Elements by class name method is available on the document element or any other element also so let’s understand it with one example here we will add one class name in the first title so the class name is message in the second one we will add the class name message and in the third one also we will add the same class name message let’s delete the fourth one now we can select these elements with the class name in this script let’s add let MSG is equal to document dot get elements by class name and here we will add that class name which is message now we will check the output in console MSG and you can see the output here it is returning the collection of three HTML element with the class name message you can see H1 do message H1 do message H1 do message so it is returning all the HTML elements with the same class name now let’s come back to the code and here we have added document. get Elements by class name we can add this get Elements by class name on any element also so let’s see the example here I will add one div and insert these two title in this div and for this div we will add one ID let’s add the ID container so total we have three headings with class name message but these two headings are included in this div with the ID container now we will add the get Elements by class name over this container so we have to store this container in one variable so let’s add let cont is equal to document do get element by ID and the ID is container now we can write cont here in sh of document we will add cont which is container and get Elements by class name now it will only give the elements within this container you can see the output here we have only two elements HTML collection 2 we have two HTML elements in this collection H1 do message H1 do message so this get Elements by class name will return the collection of HTML elements with the same class name on the document or within the element now let’s learn about query selector and query selector all method the query selector method allow you to select the first element that matches one or more CSS selector the query selector is a method of element interface we can apply this on element also here we will add one variable let MSG is equal to document dot query selector and in this query selector we have to add the CSS selector so in CSS to select this title we used to write Dot message because it’s a class name so we used to write do message to select this element in the CSS file so we have to add the same thing here we have to add the CSS selector in this quy selector that’s it so here we will print console.log MSG so first let’s see the HTML code here we have one title with this message another title with this message and third title with this message so total we we have three title with this message class name now let’s see the output in console tab here it is displaying only first element H1 class name message first heading so let’s come back here you can see we have added query selected only so it will return only first element now we will add query selected all after adding query selected all you can see it will display all the elements we have node list of three element which is H1 message H1 message and H1 message so it is returning all three headings and if I remove this all and write query selector only it will only return the first element here we have added quy selector all on document we can use the quy selector all on any element also so let’s add cont for container is equal to document do get element by ID here we will add this ID container now we will add this query selector over this container so just add container do query selector so it will give only two elements which is here second heading and third heading now you can see the output in console tab here it is displaying node list 2 it is displaying Two element so it is selecting only two elements which is in the container with the class name message now let’s come back to the previous example document do query selector all now let’s see what we can add in this query selector so we can add the class name using Dot so we can add the ID also we will add the ID and we can write this container we will add hashtag and this container because we used to write like this for CSS selector hashtag container because here we have the ID container so we can add the hashtag to select the element with the ID now we can add like this directly div so it will select this div element if we just write H1 so so it will select all the heading element with H1 tag we can write like this also div and H1 so it will select the heading within this div you can see the output here we have 2 H1 only now come back and we can select the multiple element like this div also and H1 also so it will select all the div element and all the H1 element by adding one comma you can see here we have four element node list four one is div with the container ID and three H1 tag with the class name message so basically we can add all the CSS selected in this query selector and query selector all method now we will learn about traversing elements to understand how to get the pent element how to get child elements and how to get the siblings of an element to get the parent node of the ESP specified node in the Dom tree we can use the parent node property in this body let’s create some HTML elements We’ll add one div with the ID title and within this div We’ll add one text NP tag welcome to greatest tag and for this P let’s add one class name text so we have one parent element and one child element now we will try to get the parent element using this child element so here in this script we will add let txt is equal to document dot query selector and we will add dot T text so it will select this P element now we have to get the parent so we will add console.log then txt which is the child element dot parent node this one just add this parent node and it will display the parent element of this child element so now let’s see the output in the console tab here you can see it is displaying div class title which is the pent element now let’s learn how to get the child elements we will learn about how to get the first child Element last child element and all children of the a specified element so here we will add another example just remove it and within this let’s create multiple P tag we have four text here Greatest Tag one two three and four so we have four title welcome to greatest tag 1 2 3 4 so now we’ll get the child element using this parent element now Within in this script first we will select this parent element so let parent is equal to document do query selector and write the query selector title so it will select the div now we have to get the first child last child and all the children of this div so here we add console.log and this parent then we will add first child now you can see the output in console tab here it is displaying # text because here we have some space so so this space is also one empty text node if we remove this and write it in the same line now you can see the output in console tab it is displaying the first title which is welcome to greatest tag one and if I add a space here it will display one text node now I want my text like this and I want to display the first element so here we will just just add first element child like this parent. first element child now you can see the output it will display the first element welcome to greatest tag one the first title in P tag similarly we can add last element child like this and see the output it is displaying well welcome to greatest tack 4 right so it is giving the last element which is welcome to greatest tack four now if you want to get all the child elements just add child nodes that’s it after adding this come back to the web page and here you can see we have node list text again P again one text again P so we have the empty text node then P tag let’s come back and here if I remove this a space and write everything in the same line like this now you can see it will only display four element which is 4 P element so we got the child nodes of this div now we will learn about how to select the next sibling and previous siblings of an element so in this example in this second P tag we will add one class name let’s add class name second like this so it’s easy to select this element and according to this element we will find the previous siblings and next siblings so here we will add second here also second so it will select this welcome to Greatest Tag 2 now to get the previous sibling here we will add this element then Dot and write previous element sibling that’s it you can see the output it is displaying welcome to greatest tack 1 so we are finding the previous sibling of Welcome to greatest tack 2 now just come back and here we will add next so it should give this welcome to greatest tag three because we are selecting this second one and we are adding next siblings so it will display third now let’s see the output H is dis playing Welcome to greatest Attack 3 so this is how you can select the previous siblings and next siblings now let’s learn how to manipulate the HTML elements so the first one we will learn is create element to create an HTML element we use the create element method the document. create element accept an HTML tag name and return a new node with the element type so let’s understand it with one example here we can add document dot create element and in this one we have to add one HTML tag so let’s add the div tag so it will create one div element we can store it in any variable so we’ll add let div is equal to document. create element div so it will create one div element now we can print it let’s add console.log div you can see the output on the web page it is displaying this div this div is empty right now so let’s come back here in the next line we will add div div dot inner HTML we will learn inner HTML also so here we can write any HTML code we will add one P tag and in this P we will add welcome to greatest tag and close this P now we’ll see the output here you can see one div and here we have one text in this we have one div tag and within this div we have P tag and the text is welcome to greatest tag so you can see using this document. create element we can create One D element or any HTML element and we can add any HTML code within this element and we can print it and we can also add this element on our web page so to add this element on our web page here let’s add document dot body we will add this element on the body so here we will add body dot app and child we will learn the app and child later so to insert this newly created div in this body we are adding appen child div so after adding this come back to the web page you can see we have text here welcome to greatest tack right so this is added us using this appen child div that we have newly created within this body you can see we have not added any text in div or P tag we are creating this element using this document. create element if I change it welcome to greatest tag two you can see it will be deflected here welcome to Greatest Tag 2 now we can add the ID or class name anything in this newly created element so here let’s add div. ID is equal to title let’s see here we have this div with the ID title now we can add the class name also just write div. class name title and you can see the output here D class title so we can create a new element using document. Create element and we can add the content here we can add the ID we can add the class name or any other attribute next we will learn append child method we use app and child method to add a node to the end of the list of child nodes of a a specific parent node the append child can be used to move an existing child node to a new position within the document so let’s create some HTML elements here here we will add one UL tag with the ID menu so we can easily select it here we will add some content in lii home second one is about third one is blog right you can see these elements on the web page home about blog let’s come back let me add one more here we will add project now within this script we will add let menu is equal to document do get element y ID and the ID is menu so it will select the UL element now we have to create one element and we will add that element in this UL so here let’s add let list is equal to document dot create element and the element tag name is is lii so it will create one lii element and its name is list so in this list we will add inner stml and through this inner HTML we will add one text contact like this now we can use menu do appen child list so this is the element which is here ul and this epen child will add this list at the end of this list in this list we have home about blog project so it will add the newly created list item after this project so here we have created one list item and the text is contact so this contact will be added after this project you can see on the web page here we have home about blog project and after this project we have contact that we have created using this create element and added using appen child in this UL so this newly created list will be added at the end of this list next we will learn about text content to get the text content of a node and its descendants you can use use the text content property so let’s see one example here we have the same HTML elements and this a script we have added this line that will select this UL element and after that remove this and here we will just add console. log menu so it will display the complete menu in the console tab now we just want these text so here we will add menu dot text content that’s it menu do text content and see the output in the console tab here it is displaying home about blog and project so it will ignore the HTML tag and display only text now let’s see one more thing here if I write inner text we are adding inner text and see the output still it is displaying home about blog and project but there is one difference this inner text is following the CSS also in this last one if I add a style display none so it will be hidden from the web page you can see that is not visible so this inner text will return only visible text you can see here we have home about blog and these home about blog is here on the web page but we have one more element here project which is invisible but if I write text content it will display all the HTML text content you can see on the web page we have home about blog only but here it is displaying home about blog and project so this text content is displaying all the text inside that element and inner text is displaying visual text only now we can use the text content to insert the text also let’s add menu dot text content is equal to hello so in this menu right now we have these list so it will remove this list and it will add hello let’s see the output here you can see we have only Hello in this web page so we can read and add the text using this text content on the web page next we will learn about iner HTML so inner HTML is used to add the HTML code on the web page so here we have added textt content so instead of this we will add inner HTML and see the output on the web page you can see we have hello so it is in the normal text so here if I write H1 it will add this hello text in heading so so it is in heading style hello so this inner HTML accept the HTML tags and add the text on the web page but instead of this inner HTML we will add text content now you can see what will happen it will add this as a plain text H1 is also displaying here and if I add in our HTML it will add this text and this hello text will be in the heading Style you can see this hello text on the web page next one is after method we can use after method to insert one or more nodes after the element so this is the Syntax for after method we have to add the element name then after method and we have to pass a new node that we want to add after that particular element suppose we have this menu element so we can write this menu then after method in this one we can pass a new element and we can create a new element using the create element method this after method can accept multiple nodes so we can add multiple element after this menu it can also add a string after the element so we can add multiple string s str1 s Str 2 like that we can add multiple string after this menu element so so this is the use of this after method now let’s learn about append method so this append method is also similar as append child but in the append method we can add multiple elements this is the Syntax for append methods we have to add the parent element then append then we have to pass a new element that we want to add in that parent element so this new node or new element will be added in the parent element at the end of the list of childs so what’s the difference between append and append child so this appen will accept multiple nodes and it can add string also the next one is prend Method so this is the Syntax for prepend method parent node. prepend and new nodes so it will add the new node as a first child in this parent node so this is the prepend method the the next one is insert adjacent HTML so this is the Syntax for insert adjacent HTML here we have to add one element then insert adjacent HTML method and here we have to give position and text so suppose we will add this element menu and we want to add one text at the end of this list so here we have to give the position so the position can be before begin after begin before end and after end so suppose we add before begin so this element is starting from here so this before begin position means it will add the new node before this ul and if we add after begin it will add it here at this position and if we add position before end so this is the end so it will add before end here it will be added in this line and if we add after end so it will be added after closing of this UL so let’s test it here we will add any one position I will add before end let’s add before end and here let’s add lii contact like this so here I’m adding one html text and this is the position and this is the element where we want to add this so you can see the output on the web page the contact is added here now let’s come back and if I add after begin so it will be added here at this line because this is a starting of this element and it will be added here you can see the first one is contact and after that home so this is how this insert adjacent HTML works now the next one is replace child here is the Syntax for the replace child method replace child method is used to replace the child element with the new one so we can use this syntax we will add the parent node then replace child method here we have to add the old child that we want to replace and here we have to add a new child that will be replaced on the place of old child next one is clone node method we can use clone node method to clone an element here is the Syntax for clone node method we will add the original node then clone node so this new node will have the another copy of this existing node if I add menu so this new node will have one copy of this menu element let’s print this one here we will add console.log new node you can see the output it is displaying ulli menu now let’s come back and here we can pass the argument so if I WR true it will clone this descendants also this UL element and these Li elements Also let’s come back you can see we have ul and all these Li and if I remove it or write false by default it is false we don’t need to write but if I write false you can see here we only have UL element and if I remove move it still it will be only ul and if I write true it will clone the element and all the child element also you can see ul and all three lii so this is the Clone node method next one is remove child method to remove the child element of a node we can use remove child method here is the Syntax for remove child method here we have to add the pent element and then write the element that we want to remove from the pent element so here let’s add menu and from this menu suppose I want to remove this last one so here we will add menu dot last child element so it will remove this blog you can see on the web page here we have home about blog is missing if I write menu DOT first element child so it will remove the first element which is home you can see on the web page here we have about and blog so this is the remove child method next one is insert before method we can use insert before method to insert a new node before an existing node as a child node of a parent node here is the Syntax for insert before method we have to add one pent element then this insert before method and it will accept two arguments in this one we have to add the new element that we want to add and we have to add the existing element before that existing element this new element will be added we have the pent element menu so we will add menu here and we want to add the new element before this lii that home link so here we’ll add menu DOT first element child so this new node will be added before this home so this is the insert before method so these are the methods to manipulate the HTML elements now we will learn about attribute methods so let’s understand what is attributes here I will add one HTML element input type is text we will add one ID so let’s add the ID username and we can add the placeholder also username so in this HTML tag we have added three attributes which is this one this one and and this one this is the attribute name and this is the attribute value the ID is the attribute name username is the attribute value this placeholder is the attribute name and username is the attribute value now how we can get the attributes of any HTML element using JavaScript so let’s add one script tag here where we will add our JavaScript code first we have to select this element so we can use any method to select the element let input box is equal to document. get element y ID I’m using get element by ID method and we will add this ID username after selecting the element we can find the attributes available in this HTML element so to get the attribut we will just add the element which is input box and after that just add attributes that’s it it will give all the attributes available in this HTML element so to print this in console we will add console. log and add this code inputbox do attributes after writing this let’s come back to the web page and uh you can see the console tab it is displaying type then ID then placeholder so we have three attributes in this HTML element now we have some attribute methods to get the attribute value and to set the attribute of any HTML we can check for some attribute whether it is available or not and we can also remove the attribute using the attribute methods so let’s see the first method which is get attribute so instead of this we will add the element which is input box and here we will add get attribute and in this get attribute we have to add one argument so we will add the attribute name so here we have the attribute name type so just add type like this and after that let’s come back to the web page you can see here is displaying TT so we can read the value of the attribute using the get attribute method let’s take another example here I will add this placeholder write this placeholder here now it will display the value written in this placeholder attribute so come back to the web page here you can see it is displaying username this username text is available in the placeholder attribute so this was the first method get attribute to read the attribute value now we will learn about second method which is set attribute so let’s remove this one here we will add the element which is input box on this input box we will apply set attribute and the set attribute will accept two argument so the first argument will be attribute name and the second argument will be attribute value like this here we will add the name comma value like this so let’s remove this here and here we will add any attribute name so let me add the class so the attribute name is class and here we will add one value let’s add the class name user like this so it will add one attribute which is class and the value is user now to see the updated input let’s add console.log and here we’ll add input box so it will display this complete element on the console so let’s come back to the web page here in this console you can see we have the input element with the type text ID username placeholder username and there’s one more attribute which is class user that we have added using this input. attribute class user so this was the set attribute method now we will learn about next one which is has attribute so it will tell us whether this attribute is available on the element or not it will result in true or false so here we will add another example we will add the element input box then has attribute and this will accept only one argument so in this one let’s let add class and it will return one true or false value so we can directly print this one so just add console.log input box has attribute class so you can see in this input field we have the type ID and placeholder we don’t have class here so it should return false let’s see the output you can see it is displaying false now let’s come back and instead of this class we will add ID so it will return true let’s come back to the web page you can see it is displaying true in this console so this has attribute will return true or false value if the attribute name is available in the input field it will return true if this attribute name is is not available in the input field then it will return false so using this has attribute we can check the availability of that particular attribute on the element next we will learn about another method which is remove attribute that will remove the attribute from the element so in this one we will add element then remove attribute and in this remove attribute we will add one attribute name that we want to remove so here we have type ID and placeholder so let’s try to remove this placeholder just copy this one paste it here so this remove attribute will remove this placeholder from this input element now we will just print this input element in the console we will add console.log input box and now we will see the output in console here we we have the input element and in this input element we have type text ID username but here we don’t have the placeholder because in this code we have added remove attribute placeholder so it will remove this placeholder attribute from this element so these are all four attribute methods now we will learn about manipulating elements a style to manipulate the style of the element we have the property called Style and we can use this a style property to get or set the inline style of an element so here we have the HTML element which is input and in this one we don’t have any inline style so let’s add one style here and here we will add the background color value is red and let’s add one more CSS property here that will be for font size 20 pixel so in this HTML element we have added the inline CSS in this one we have added the background color and font size now to get these inline CSS we can use the style property on this element so here let’s add the element which is input box do style so it will return the CSS properties available in this input field in the inline CSS it is returning some value so we can add console.log and this code now you can see the output in the console tab in this console you can see it is displaying background color and font size because here we have only two inline CSS properties which is background color and font size so this element do style will return the inline CSS available in the element now if if you want to return the background color value or the font size value then we can write input box style dot background color like this after adding this come back to the web page here you can see it is displaying red background color value is red now if you want to see the value of this font size here we will add font size and you can see the output here in the console tab it is displaying 20 pixel so we can get the property name also and value also now we can use this style property to set the style of the element so let’s add input box and on this input box we will add a style and in this a style let’s add one new CSS property let’s add padding padding is equal to 10 pixel after adding this we will display this input in the console so we will add console.log input box so it will display this input field in the console tab where it will add the padding also so let’s come back here you can see we have this input element in this one we have the style background color then font size and after that you can see this padding let’s select this one here you can see padding and the padding value is 10 pixel so using this style property we can get the inline CSS and we can also set the inline CSS now we have one more option to add the inline style in the HTML element that is using CSS Tex text so here we will add the element then style then CSS text and in this CSS text we can add the CSS so let’s add width 200 pixel after adding this let’s print this element in the console you can see the output here on the web page it is displaying this element with the style width 200 pixel here we have only one CSS property which is width 200 pixel let’s come back to the web page we have added CSS text with 200 pixel so it will override the existing inline CSS you can see we already have background color font size but it is not available on the web page why because we are adding width 200 pixel using this CSS text so it will override completely it will remove this and add this one but if you want to keep the existing CSS also and add this one also then you can use the concatenate to perform the concatenate we will just add plus before this assignment operator like this after adding this again come back to the web page now you can see in this input field we have the multiple CSS properties which is background color then we have font size and width also so after adding this concatenate we can use the existing inline CSS also and we can add a new inline CSS using this CSS text we can add multiple CSS properties at the same time you can see we have added width so we’ll add more CSS properties just add semicolon and add another CSS property let’s add height height will be 100 pixel now we will come back to the web page you can see height is also applied in this input field you can see it in the console also here we have height 100 pixel so using this CSS text we can add multiple CSS properties in the HTML element as a inline CSS so this was the use of CSS text for modifying the inline CSS of the HTML element now we will learn about get computed style method currently we have learned how to modify and get the inline CSS properties of the HTML element using JavaScript now how to get the CSS properties written in the external CSS so let’s remove the CSS from here remove this inline CSS and we will add the CSS properties in this head here we will add style tag within this style we will add the CSS selector input and for this input we will add the background let’s add the background color red and font size 12 pixel so we have added two CSS properties for this input element now how to get these CSS properties to get the CSS properties of this input element we will use get computed style method so let’s see the syntax first this computed style method is a window object so we will add window do get computor style and in this one we will add the element we can add one more argument that will be C element so this is the Syntax for get computed style in this one we will add the element if you want to get the CSS property of the element and if you want to get the CSS properties of the seudo element then you have to add the element and it C2 element and now let’s see the example for this input field so here we will add window do get computered style and in this one we will just pass to the element which is input box now it will return the CSS properties available on this input field so we can print it using console console. log and add this one now let’s come back to the web page to see the console tab here it is displaying all the CSS properties that are applied by default on the element in this one we will find the background color also you can see the background color here and there will be font size also it is here font size so now we can get the value of the particular CSS property so from this input box we will add font size now it will display the value of this font size you can see it is displaying 12 pixel that we have added here in external CSS now let’s add the background color we are adding this window. get computed style then passing this element and from this element we’ll get the value of this background color let’s come back to the web page here is displaying the color now let’s come back in this one we will add one more property let’s add the width of 300 pixel and here we will add dot width then we will see the output it is displaying 300 pixel so using the git computer style method we can read all the CSS properties applied on any HTML element now we will learn about class name property class name property return a list of classes separated by space so let’s take one example here we will add one title in H1 tag so let’s add the text greatest T and and with this H1 we will add one ID to select this element we will add the ID title and let’s add some class name also so let’s add the class main the first class name let’s add one more class name which is message so in this one we have added two classes which is Main and message now to get the class name of this element we will use the class name property of JavaScript so let’s add the JavaScript here in this script tag first we have to select the element so let’s add the variable with the name title and select the element using document. get element by ID and write the ID title after that we will add title dot class name that’s it it will return the list of classes available on this element so it is returning some value then we can print this one in console let’s add console.log title dot class name that’s it now we will come back to the web page now it is displaying the classes available on this element which is Main and message so we have two classes we can use this class name property to add a new class also so let’s come back here and here we will add title dot class name is equal to new so this will add one class name which is new in this element let’s remove this class name here we will display the complete element in the console using this console.log title let’s see the element here you can see it is displaying this HTML element with ID title and class new we have only one class which is new but in this HTML you can see we have already added Main and message so this will override these classes here we have two classes that will be removed and this new will be added in this class but if you want to keep the existing class also and new one also then you can use the concatenate using this plus and this assignment operator after adding this here we will add a space and let’s come back to the web page now you can see the same element H1 here and in this element we have class main message and new so we have total three class here so using this class name we can read the class name of the HTML element and we can add a new class also now we will learn about class list property class list return the collection of CSS classes so let’s see if we add class list and it is returning some value so we will print this one title. classlist like this we are just adding title. class list and you can see we already have Main and message class in this element now we will come back to the web page in this one you can see we have a list where we have Main and message class so we have two classes so this class list is returning the collection of classes available in any HTML element so this was the first use of this class list to display or get the class list of any HTML element now we can use this class list to add the class to remove the class so let’s understand how we can add a new class using this class list so in this title element we will add classlist do add like this we are adding class list do add and in this one we can add a new class just add new like this that’s it after adding this we will display this complete element in console tab we are displaying this title let’s come back to the web page here you can see we have this element with three classes main then message then new let’s change the size so you can see we have total three classes main message and new now let’s come back if I add multiple classes we’ll just add a comma and add a new class name like new two so we are adding another class name like this we can add multiple classes using this class list you can see we have more class name here main message new and new to so using this class list. add we can add a new class name in the stml element now we can use this class list to remove any class so instead of this add just type remove class list. remove and what we will remove we already have Main and message so let’s remove this message write it here in a quote and come back to the web page here you can see in this element we only have one class which is main now just come back and we can remove both classes so let’s add comma and write main so it will remove the another class also we can type multiple class name here and it will remove all that classes from that element you can see this element in this element we don’t have any class we have the class attribute name here but we don’t have any value in this class next we can use this class list to replace any class so instead of this remove we will add replace and to replace this one we have to add the existing class name and new class name so in this HTML element we have message so write message here and we are adding a new class name instead of this message so we’ll add MSG so instead of this message we will replace it with MSG now just come back to the web page you can see the output in console here we have class name Main and MSG so we are replacing this message class with MSG class using this class list. replace place now we have one more option to check whether the class is available or not for that here we will add class list do contains and in this one we will add any class name so this message is here we are adding message so this will return the value either true or false if this message is available in this element then it will return true if it is not available it will return false so we’ll just print this one remove it from here add it in console and come back to the web page you can see it is printing true because this message class is available in this element so we are adding class list do contains and class name this class name is available in the element that’s why it is returning true suppose we add MSG and this MSG is not available in this element then it should return false you can see the output it is false now we have one more thing which is toggle let’s see this example here we will remove this one we will just print this complete element in console and here let’s add title dot class list. toggle and in this toggle we can add any class name suppose we add message what will happen if this message class is available in the element it will remove it this toggle means if the class name is available it will remove it and if it is not available then it will add that class name in the element so what will be the output this message is already there and we are adding toggle message so it will remove this message let’s see the output in console here you can see class main here we have only one class which is main so this toggle removed this message class now instead of this message we will add new so what will happen this new is not available here so it will add this new in this element let’s come back to the web page again and now you can see we have total three class in this element which is main message and new so using this class list. toggle we can add and remove the class from the element if the class name is already there it will remove it and if it is not there it will add the class so this was all about class list property in JavaScript now we will learn about JavaScript events an event is an action that occurs in the web browser when we click on the web page that is a click event when we move cursor over the web page that is mouse move event and when the web page loads that is a load event like that we have multiple type of events in JavaScript let’s create some HTML elements here I will create one div with the ID container and within this container we will create one button with the button tag and button type will be button and here we will add the text click here now we will come back to the web page here you can see this button click here if I click here nothing is happening because we have not added anything so let’s come back you can see we have added the button and clicked on this button but when we click on this button we are actually clicking on the button this div this body and this HTML and this document also so when we click on any element actually we are clicking on the all the patent elements also that means this di with the ID container then body then HTML and this document and in modern browser this click goes up to window object there are two event models that is event bubbling and event capturing so when we click on the button click a start from the button then goes to div then goes to body then goes to HTML and then goes to document so the event flows from the most specific element to the least specific element that is event bubbling but when the event start from the least a specific element it means it starts from the document then event flow to HTML then it flows to body then it flows to div with the ID container then it comes to the Target element which is button so this event model is known as event capturing when the event starts at the least specific element and flows towards the most specific element we may respond to these events by creating event handlers an event handler is a piece of code that will be executed when the event occurs so when we click on this button we will add some code that will be executed after clicking on this button so that code is known as event handler and event handler is also known as event listener so there are three ways to assign event handlers so first one is using HTML attribute for each event there is event handler and their name typically begins with on so let’s see the example we have click event and for this click event we have the event handler on click like this so let’s assign this on click in this HTML element as an attribute so in this HTML element we will add on click so this is the event handler of the click event and within this quote we can write the JavaScript so let’s add a simple JavaScript line console.log so it will log one message in the console of the browser in this one let’s add some text here we cannot add double code because we have already used so I’ll add single quote button clicked so this button clicked message will be printed in the console when we click on this button so let’s see this on the web page this console is Ed right now and if I click on this button that is here in top left corner you can see this message button clicked this event handler attribute can call one function also so let me remove this HTML code we have added event handler which is on click and this on click will call one function so here let’s create one function in a script tag in this script We’ll add one function with the name display MSG that will display message here we will add console.log button clicked let’s add some more text button clicked from FN which means button clicked from function now we will call this function when we click on the button so in this attribute we will call this function write this function here so this is a function call now let’s come back and you can see this console is empty and if I click on this button again you can see the message here it is saying button clicked from FN it means button clicked from function now just come back when the event occurs the web browser passes an event object to the event handler so to understand this one let’s remove this function here and we will add JavaScript code in this attribute so here let’s add console.log and when we click on the button the JavaScript will pass the event object so we can write that event object here event now we can see what is there in this event object let’s see the output so you can see here we have one object now this event object has some properties that we can access so from this event we can find the type event. type let’s see it is displaying the event type event type is Click let’s come back we can add the target so we will get the target element on which the event occurs when we clicked on the button it is displaying the entire button element with all the attributes so it is giving the target element we can also use this keyword inside the event handler and this keyword inside the event handler refers to the Target element let’s see the example example here in this event handler we will try to print this this keyword will refer to the Target element let’s see the output when we click on the button you can see again we got the target element which is button so this keyword inside the event handler refers to the Target element from this keyword we can find the properties of this element so let’s add one ID here I will add the ID is equal to BTN and here we will add this do ID so when we will click on the button it should display the ID value let’s see if I click on the button it is displaying BTN now just come back and instead of this do ID we can simply add ID from the event handler we can directly access the elements property so we are adding console.log ID so it should display this ID value let’s see if I click on the button we got the ID value which is BTN if I write type which is here we will get button it’s here so this was the first method to add the event handler in HTML as HTML attributes now the second method is adding event handler name in the JavaScript so let’s remove this on click from here we have one button let’s remove this type also it will be simple so we we have one button with the ID BTN now we will add the script where we will add the JavaScript So within this script first we have to select this button so let’s add let BTN is equal to document. get element y ID and we will add the ID BTN so we have selected this button element now on this BTN we can add the event handler just add on click and now we can add the code that will be executed when we click on the button so here we’ll create one function and within this function We’ll add console do log and this will print message button clicked after that let’s come back to the web page click on the button and you can see the output in the console button clicked let’s come back you can see here we have the HTML element and in this one we have added the JavaScript in this JavaScript we have added on click event handler name and added one function that will dis play one message here also we can write this keyword that will refer to the Target element and from this we can find the ID this do ID let’s see it is BTN now to remove the event handler we will simply add element which is BTN do onclick and assign null that’s it it when we assign null in this event handler it will remove the event handler so this was the second method to assign the event handler now we will learn the Third Way of assigning event handler so in JavaScript we have two methods with the name add event listener and remove event listener these are two methods that handles the event ad event listener will register an event handler and remove event EV listener will remove an event handler so let’s see the example of add event listener the add event listener accept three arguments the first one will be event and the second one will be one function this function will be executed when the event fires and the third argument is use capture so the third option is optional because by default it is false this use capture is a Boolean value it can be true or false so by default it will be false and we can remove it it is related to the event bubbling and event capturing so let’s ignore that third parameter we will pass to argument event and one function so let’s see one example so let’s try to add this add event list on this button remove it here we will add BTN do add event listener and we will pass first argument which is event so the event will be click we are adding The Click event then a comma here let’s define one function here I’m adding function like this so this is the function defition within this curly Braes we can add the code that will be executed so here let’s add console.log and message button clicked so we have selected the button using get element by ID then on this button we are adding add event listener method that will assign the event handler so in this event listener we are adding first parameter and second parameter first parameter is event so the event is click and the second parameter is a function so we have declared one function here this function will print one message in the console tab when we will click on the button let’s see this output on web page click on this button and you can see the message button clicked as I already said when the event occurs the JavaScript passes the event object to the event handler so in this one we can pass the event object and we can find the type from this event event. type let’s see the output if I click on the button we got event type which is Click now instead of adding this Anonymous function we can add the external named function also so let’s remove it here we can add our second parameter before adding that second parameter let’s create one function with the name display message and this display message will log one message message button clicked now we can refer this display message function here like this after adding this let’s come back and if I click on the button again you can see the message button clicked so we can add the event name and one function it can be a Anonymous function or it can be a named external function we can refer to that external named function with the function name without the parenthesis so this was add event listener method now we will learn the remove event listener method the remove event listener removes an event listener that was added using add event listener so here we have added the event listener using add event listener method now we can remove it using BTN dot remove event listener again we have to pass the same arguments just copy and paste it here so this remove event listener will remove the event listener that was added using this add event listener you can see here I have added the external named function if I add one Anonymous function here then we cannot remove move that event listener using this method so we have to use the external named function when we want to add the event listener and remove the event listener now let’s know about some of the useful JavaScript events so the first one is mouse move event Mouse move event fires repeatedly when you move the mouse cursor around the element and second one is mouse down event when you press the mouse button on the element this event will fire next one is mouse up when you release the mouse button on the element then this event will fire next event is mouse over event when the mouse cursor move from outside to inside the boundaries of the element then Mouse over event occurs next one is mouse out when the mouse cursor is over an element then moves to another element then Mouse out event occurs next one is key down event key down event fires when you press the key on the keyboard and it fires repeatedly while you are holding down the key next one is key up event this key up event files when you release a key on keyboard next one is key press so the key press event occurs with when you press a character keyboard like ABC it files repeatedly while you hold down the key on the keyboard next one is scroll so a scroll event occurs when you scroll a document or an element the scroll event fires we will see more examples of events when we will create the JavaScript projects now we have completed the basic of JavaScript next we will create some JavaScript projects in this video we are going to learn how to create a Notes app using HTML CSS and JavaScript here on my computer screen you can see one button create nodes if I click here it will open one input box and here we can type our text note this is note one so you can add your text note in this white box and if I click on this button again it will again open a new input box where we can add another note and if I click on this delete icon it will delete this note we can delete all the nodes and let’s add the text again two so we have added two notes here this is Note One Note Two And if I close this browser and open the browser again let’s see you can see this note is still displaying here because we have added the local storage that will store the notes in the browser so we will create this note app that will store the text note in the browser using HTML CSS and JavaScript so let’s start this video here I have this folder called Notes app in this one I have one HML file one CSS file and another folder called images in this images folder I have some icons that I will be using on this web page you can find these images download link in the video description let me open these files with my code editor which is Visual Studio code you can use any code editor so this is the HTML file where I have added the basic HTML structure and this one is the CSS file where I have added margin padding font family and box sizing these CSS properties are applicable for all the HTML elements in this HTML file I have added this title that is the title for the web page then we have added the link tag with the file name style. CSS so it will connect the HTML and CSS file next we have to add the HTML codes in the body tag that will be displayed on our web page so within this body let’s create one div with the class name container now in this container we will add one title in H1 so here we are adding one title notes and after this title there will be one button so let’s add one button and in this button we will add the button text create notes after adding this let’s come back to the folder and open this HTML file with any web browser so you can see this text here notes and create notes button now I will close this browser and I will open it with the visual studio code extension called live server so it will refresh the web page automatically whenever we will add any changes in the code file you can see the same web page but the order has been changed now we have to add some CSS so just come back and copy this class name container and come back to the CSS file within this CSS file let’s add do container and here we have to add the width then we will add minimum um height and in the background we will add the linear gradient color so let’s add the background linear gradient and two color codes then we will add color that will be white and let’s add some space from the top padding top and padding left that will be spaced from the left side after writing this you can see the changes in this web page the text color is white and the background color is linear gradient now let’s come back and uh with this text we have to add one icon also so just in front of this notes we will add one IMG tag so here we will add IMG and SRC and file name images SL the file name is noes. PNG and in this button also we will add one icon so here also let’s add this IMG tag and replace the file path so it is edit.png so we have added two icons with the tag in the nodes and create nodes button you can see this icon and this edit icon in the button now we have to add the CSS for these icons and font size so let’s come back after this container again add container and H1 for the title here we will add display Flex align items Center then font size will be 35 pixel and font weight 600 now within this H1 we have added one icon with the IMG tag so we are adding IMG here and for this image we will set the width it will be 60 pixel so this size for the note icon looks good next we will Design the button so let’s come back and here we will add container then button and in this button we have image so for this image again we will add the width 25 pixel and margin from the right side this will be H pixel let’s copy container and button now we will Design this button using CSS so let’s add display then align items background will be linear gradient two color code button text color will be white and uh font size outline zero and Border zero border radius will be 40 pixel let’s add some padding that will be space inside the button 15 pixel from top and bottom and 25 pixel from left and right side then margin that will be space outside of the button 30 pixel 0 and 20 pixel cursor will be pointer so after adding this you can see this create notes button looks good next we have to add one input box where we can type the text note so let’s come back and uh after this button we will add one tip with a class name nodes container and in this one let’s add one P tag in this P we will add content editable true and we will add one class name also so the class name is input box so it is not visible here because we have not added any text in this P tag so let’s come back and we have we have the input box just copy this one and come to the CSS file write this input box with the dot and here we will add position relative width will be 100% And the maximum width will be 500 pixel then mean height background will be white so we have added width and height in this P then we will add the color padding of 20 pixel margin 20 pixel and zero then let’s add outline none border radius 5 pixel so that the corners will be round after adding this the input box looks good and in this input box we can type anything now we need uh delete icon also so let’s come back and uh before closing of this P tag here we will add a space and before closing of this P tag we will add one IMG tag write the file path images SL delete.png it is delete icon and you can see this icon here next we have to set the size and position for this delete icon let’s come back here we will add this input box then IMG for this image width will be very small 25 pixel Position will be absolute then it will be at bottom 15 pixel space from the bottom and 15 pixel space from the right side cursor will be pointer after adding this you can see perfect position for this delete icon now this input box is displaying by default so we have to to hide this input box and it will be displayed whenever we will click on the create note button and every time you will click on the create noes button it will run a JavaScript and that JavaScript will display the input box so let’s come back and here we have the P you can delete this P tag or command it let me commment this one so it will be disabled and right now you can see we have the text and button we don’t have any input box now we will display the input box with the help of JavaScript so let’s come back and here we’ll click on this icon to create a new file and write the file name script.js so this is our new file script.js next we have to connect this script file with the HTML file so let me come back to the HTML file and just above this closing body tag we will add script SRC and the file name which is script.js now the HTML file and JavaScript file are connected let me open the folder again and here you can see one new file which is a script.js in the same place where we have added HTML and CSS file now let’s come back to the JavaScript and here we will add some variables so let’s add const nodes container con nodes container equal to document. quy selector do nodes container now we will duplicate this line it will be create BTN and here we will add the class name BTN and uh in this button we will add one class name class BTN after that we will add one more variable let nodes equal to document dot query selector all dot input box so here we have added three variables notes container which is for this notes container class name then create button which is for this create button and then we have added another one notes that is for this one input box this input box is not there but we will add it using JavaScript so we will add the multiple P tag with the class name input box so here I’m adding query selected all that will select all the nodes after that let’s add one function then I will explain you each line here we have added create button add event listener it means whenever we will click on the button that is here BTN so it will execute these codes and first it will create one variable called input box and it will store one element document do create element by P so it will create one p element and it will store it as input box then it will create another element with the IMG tag and it will be stored as IMG now in the P element which is input box it will add one class name called input box then in this P element we will add one more thing which is content editable true so we are adding input box set attribute content editable true so it will add one P tag then in the P tag it will add one class name input box then it will add one attribute content editable true and after that we have added img.src we have created one more element IMG and in this Source we will add one file path that is for the delete icon images /d delete.png so it will add this image IMG srz images /d delete.png now we have to display it so we have to display this in the notes container so you can see we have added noes container do appendchild input box it means this input box will be displayed inside this noes container and after that we have added the and child IMG it means this image will be displayed inside this P tag which is input box so after adding this let’s come back to the web page and click on this button you can see it is adding one new input box with the delete icon and we can type anything in this input field it is working now click again it will display the another input field now if I click on this delete button nothing is happening so we have to add one more thing this delete functionality so let’s come back and here we will add this one notes container add event listener again we will add the click event then function if e do Target dot tag name if the target is IMG then e do Target dot so we have added nodes container event listener click so when we will click within this notes container and if the target element is IMG then it will remove that parent element so let’s come back click on this button it will display one input box and here we have the delete button let’s click on this delete icon and it will remove that pent element let’s click again and click on this delete you can see it is deleting the parent element so it will hide that input field this delete is working fine and we can also write something here hello this is new video right now we have added two notes and if I refresh the website you can see it will be disappeared because we have not stored these things in the browser so we have to add the local storage that will store the notes in our browser every time we will open the browser it will be stored and displayed as it is so let’s come back after these variables let’s add some space and here we will add one function update a storage data storage and after that we will add local storage do set item and write the name noes and what we have to store here we will store noes container do inner HTML so whatever is written in the noes container inner HTML that will be stored in the browser with the name notes so whenever we will call this update a storage it will update the data in our browser so let’s copy this one and add it here after deleting it it should be updated so in the next line we will add update a storage next we need one more thing if we write anything in the P then also it should update the data in the browser so here we will add the another condition which is L if here we will add nodes equal to document do query selected all input box now for all the nodes it should update the data in browser so here we will add noes dot for each n sort for the nodes ENT do on key up equal to function and here we will update a storage so it will update the storage when we will start typing edit anything in the P tag next we need one more thing when we close the browser and open the browser it should check the local storage and if there is any data in the local storage then it should display that particular data as a note so let’s come back here at the top after this variables let’s add function so notes notes container do iner HTML equal to local storage dot get item and the item name is notes so if this notes is there in the browser then it will be displayed on our web page just we have to call this function so notes just copy this one paste it here so notes will call this function and it will display this local storage in the container HTML so let’s see how it works if I refresh the web page you can see it is still displaying the note one and Note 2 let’s delete the note one here we have this is Note 2 let’s refresh the website you can see still it is displaying Note 2 so this local storage is working next we will add the one more last thing here will add here we are adding document do add event listener key down event and if the event key is enter Then document. exe command is insert line break and event prevent default it means when we will click entered in our keyboard then it will add one line break in the P tag and it will prevent the default feature of the enter key now let’s see here we will create a new note note one enter line 2 Enter line three refresh the web page you can see it is displaying as it is so finally we have completed this online note app using HTML CSS and JavaScript with the local storage in this video we will create a very useful JavaScript project which is simple quiz app you can create this squiz app or website with the help of HTML CSS and JavaScript let’s see how this squiz app works you can see this question here then we have four options if I select the wrong answer you can see it will become red and the correct answer will become green and now we cannot change our selection now we will click on the next button and if I select the another option let’s select this one and if it is correct then it will be highlighted with the green color and now we cannot click another option we have to click next and here if we will click on this one if it is correct it will become green and let’s click on the next one and now we will select any wrong answer so you can see it is displaying the red color and the correct answer is highlighted with the green color I have added only four questions here if I click on the next button you can see it will display our score you scored two out of four because we have given only two correct answers let’s click on this button play again and if I select the correct answer and again this one this and this one and click on the next you can see it is giving the correct score which is four out of four we will create the squee app using HTML CSS and JavaScript and I will explain you step by step now let’s start this tutorial to create the JavaScript quiz app here in this folder I have one HTML file one CSS file and let me open these files with my code editor which which is Visual Studio code you can use any code editor if you don’t know how to create the HTML and CSS file I will add the video link in the description this is the HTML file where I have added the basic HTML structure and this one is the CSS file where I have added the margin padding font family and box sizing these CSS properties are applicable for all the HTML element in this HTML file I have added this link tag with the file name style. CSS so it will connect the HTML and CSS file and here we have the the title quiz app easy tutorials next in this body tag we will add one D with the class name app next we will add the CSS so come to the CSS file and here first we will add the dark color on the complete web page so we will add body tag and for this body let’s add one background here we will add one color code and next we will add the CSS for the app so just copy this one add it here in this CSS file with the dot because it is a class name here we will add background so the background will be white after that we will add the width 90% and maximum width will be 600 pixel then we will add the margin 100 pixel from top left right Auto and zero from the bottom then border radius so the Border radius will be 10 pixel so the coordinates will be round by 10 pixel after that we will add the padding of 30 pixel that will be a space inside the box after adding this let’s come back to the folder and open this HTML file with any web browser so you can see this color on the complete web page and here we have the box in the white color I will close this browser and I will open this browser with the visual Studio code extension called live server so that it will refresh the web page automatically whenever we will add any changes in the code file so you can see the same web page again but the URL has been changed after that let’s come back and uh within this app we have to add one title so here we will add one title in H1 simple quiz and after that we will add one another div with the class name quiz and within this we will add one question in H2 so let’s add the H2 and here we will add one ID so the ID is question and let’s add any text here so we will add question goes here like this and now you can see this text simple question and question goes here after that we will add some options for the particular question so here we will add one div with the ID answer buttons and within this answer buttons we will add four buttons so let’s create the first one and in this one we will add the class name BTN and here we will add the answers so let’s add the text answer one now we will duplicate this button and we will change the text 2 3 and four and the class name is same after adding this you can see four buttons here after this question answer 1 2 3 4 next we have to design this using CSS so let’s come back and uh here we have the class name quiz so just copy this one and come to the CSS file before the squeeze we have the text in H1 so we will add the CSS for that text so let’s add do app and H1 where we have added the text so for this one we will increase the font size then we will change the color font weight and border bottom then we will add the padding at the bottom now you can see this line here after this text after that we will add that class name quiz and for this quiz we will add the padding it will be 20 pixel and zero after that in this squeeze also we have text which is the question in H2 so here we will add do quiz and H2 so for this question we will add font size so the font size will be 18 pixel then we will change the color and font weight and uh here we have added font weight it will be font size font size 25 pixel now it is good next we will Design these buttons which is answer button so for this button we have added the class name BTN so come to the CSS file here we will add the CSS for BTN so for this button we will add the background so the background will be white after that we will add the color that will be the text color and font weight font weight will be 500 then width will be 100% so it will be full width and border of one pixel solid and this color then we will add the padding that will be a space inside the button and margin 10 pixel from top and bottom and zero from left and right after this padding and margin we will add text align left and uh border radius will be 4 pixel and cursor pointer you can see these buttons looks good next we have to add the hover effect on these buttons so let’s come back here we will add this one and hover we will add the background this will be the background color code and after that we will add the color that will be the text color white and in this one we will add the transition all 0.3 seconds now if I take cursor you can see the background becomes black and the text becomes White next we have to add one more thing which is the next button at the bottom of these answers so let’s come back and uh here after this button and this tib here we will add another button and with this button we will add the ID next BTN and the button text is next after adding this you can see next button at the bottom so we will add the CSS for this next button so let me come back and copy this ID add it here in the CSS file with the has tag because it is an ID here we will add the background then color font weight and width width will be small 150 pixel then we will add the border border will be zero and padding of 10 pixel then margin 20 pixel Auto and zero border radius will be same which is 4 pixel and cursor pointer after adding this you can see this next button here but we have to move it in this Center so here we will add display block and now you can see it is horizontally centered right now this button is displaying so we have to hide this button and this button will be displayed once we will select any option from these answers so let’s come back and here we will add none so the button will be hidden you can see that button is hidden next we have to add the JavaScript to display the correct questions and we can select the answers so let’s come back back and here we will create a new file click on this icon and write the file name script.js this is the script file here we will add our JavaScript next we have to connect this script file with the HML so let’s come back and above this closing body tag here we will add a script tag script SRC equal to script. JS now our HTML file and JavaScript file are connected here we can add our JavaScript so in this Javascript file first we have to set the questions so here we will add const in this Con we will add the name of the variable so it is questions equal to here we have to add the questions so let’s add the first one like this question and write the question text then we have to add the options for this question so here we will add answers here I have added the first answer and correct is equal to false because it is a incorrect answer let’s duplicate it and we will add the other answers here and the second answer is correct so here we will add true so this is the first question and the list of answers now we’ll add the other questions in the same format so here let’s add one comma and we can add this second question here so you can just copy this one and paste here and update the text so I have updated all these questions and answers you can see in front of the correct answers I have added true and other are false here also I have added true and these three answers are false after that we will add another variables in this HTML file I have added this ID question and answer button and next button so we will add the variables for all these three elements so come to the script file here we will add const question element equal to document. get element by ID question which is this one next we will add the variable for this one duplicate this line add this ID here and here we will add the answer button now duplicate this and it will be next button and the ID which is next BTN now whenever we will start the quiz and give the answers the question number and the score will be changing so we will create variables to store the question index and score so here we will add let current question index so the index will start from the zero then we will add let score equal to zero next we will add one function and let me write the code then I will explain you here I have added one function start quiz so when we will start the quiz it should reset the current question index zero and score zero when we will start the quiz here we are adding inner HTML next because at the end we will change the text to the restart or replay so when we will start the quiz again the button should be next and after that we are calling this function so questions so it will set the index zero score0 and set the text next for the next button then only it will call the another function so question that will display the questions now we’ll create this function here in this so function I have added let current question equal to questions. current index so if you will see this list list of questions here we have the first set of question and answer then second then third and fourth so we will get the first question if we’ll add the index zero we will get the second question when we will add the index one so that is written here questions and index number so that will be the current question and we need the question number also so if the index is zero question number will be one if the index is one question number will be two so here I have added + one that will be the question number then in the question element which is this one this is the question element so here we will update the text with the inner HTML so we are adding question element inner HTML equal to question number then one dot and after that the current question and current question dot question so the current question will be this one and here we have the question this one so we will get this text so after adding this we have to display the answer from the current question set so here we will add the code to display the answers so let’s add current question dot answers dot for each here I have added current question do answers so it will come here suppose the current question is this one and it will go here answers and in this answers we have the text and correct so we have to display these text in the buttons so we will add document. create element and the tag name button so it will create one one button tag and we will save it as a variable called button and in this button we have to add one text so to add the text we will add inner HTML and in this inner HTML we will add the answer. text so answer is this one answer. text so it will add the first one then we will add the second one like that so it will add the text in the button then in the button we have to add one class name so we are adding button. class list do add and the class name BTN so it will add this BTN class name in this button after that we have to display this button inside the div which is here answer buttons this div is here so we have to display that button inside this div so we are adding answer button do appen child button so after adding this it will display the question with the question number and it will display the answer now we have to call this a start quiz function to display the output so let’s copy this one and add it here at the bottom start quiz so it will call this a start quiz function and it will set the current index z a score 0 and button text next then it will call the so questions and this so questions will display the question with the question number and uh it will display the answers in the button so after adding this let’s come back to the website and here you can see it is displaying the question with the question number one then we have the previous text that we have added in the HTML file which is Answer 1 2 3 4 then we have our answers that we have added with the variable here you can see the answers for the first question Sark blue whale elephant and jff so you can see these answers here but we have not added click function here right right now so now let’s come back and we have to hide these things to hide these things we have to reset the previous questions and answers so let’s come back and uh here we will add one function before displaying the question here we will add one function reset a state that will reset the previous question and answer now we have to Define this function so let’s add it here function reset state in this reset State let’s add the next button dot style do display it will be none then we will add while answer button it will will be buttons s and here also we will add buttons in this one so answer buttons DOT first child so suppose it has a child element then we have to remove that here we will add answer buttons dot remove child answer buttons DOT first child so it will remove all the previous answers and here also we have added answer button it will answer buttons yes answer buttons do app and child so after adding this let’s come back and here you can see the first question with the question number and list of options and if I click here nothing is happening next we have to add the click function on these answers so let’s come back here we will add button dot add event listener click and here we have to add one function name so when we will click on the answer button it will call this function select answer and before this click event we will add if answer dot correct so if it has some value then it will add button dot data set dot correct equal to answer dot correct so it will add the true or false in this data set correct from here this false true it will add in this button data set now we will add the function which is Select answer so let’s define this function above this a start quiz so here we will add function so when we will click on that uh button it will add the selected button element in this variable selected vtn and then it will check the selected vtn and data set true so if the data set is true then it will add the class name correct and if it is not true then it will add the class name incorrect now for these class name we have to add the background color so we will change the background color for the correct and incorrect class name so let’s come back to the CSS file here we will add correct and background in this background we will add one color code now we will add the background for the incorrect class name Incorrect and this background color after adding this let me come back to the website and if I click on the first one you can see the background becomes red because it is incorrect if I click on the second one you can see it becomes red because it is correct and if I click on the third one you can see it is red and the fourth one is red now we can click on any number of times so we have to disable the click after selecting one answer and when we will select the wrong answer it should automatically highlight the correct answer with the green color so to add that one let’s come back here in the subscript after that we will add so here we have added aray from answer buttons children for each so for each button it will check the data set if it is true then it will add the class name correct suppose we have selected the wrong answer then it will go and check the other answers and if it is true then it it will add the green color with this class name correct and after that it will disable the button so we cannot click on the any button and after that it will display the next button so here we are adding next button style. display block so it will again display the next button so that we can go to the next question so after adding this let’s come back to the website and if I click on the first one which is the wrong answer you can see the second one becomes green because the second answer is correct and it is displaying the next button and now we cannot click on the any other button let’s refresh the website and if I click on the correct answer it is displaying the green color here and now we cannot select any other next we have to hide the hover effect when we select the button so let’s come back and uh in this CSS file here we have added BTN hover so in this one we will add one more thing h and uh not disabled so the hover effect will work when the button is not disabled and when the button is disabled the hover effect will not work and we will add one more thing here we will add BTN disabled and uh cursor no drop after adding this let’s come back and refresh the website if I click here you can see we will not get the hover effect now and the cursor becomes red we cannot click on any button we can just click on the next button we have to add one more thing when we will select the correct answer the score should be increased so let’s come back and here we have added the class name correct in this one so here only we will add one more thing score Plus+ so it will increase the score by one next we will add the function for the next button so here we will add next button do add event listener and the event is click here we will add add a function and in this one we will add if it will check the current index if the current index is less than the length of the question it means the number of question is four then the question length is four so if the index is less than that then here we will add one function handle next button or else it will add a start quiz suppose if there is no question and we will click on that button so it will restart the quiz and here we have to Define this function handle next button so above this one here we will add function handle next button and in this one we will add current question index Plus+ it will increase the question index y1 when we will click on the next button and again we will add if current question index less than question length then so question function with the updated question index else it will display the score so score so if there is another question it will display the another question and if it is not there then it will display the score when we’ll click on the next button next we have to Define this function so cord so here let’s add function sour score and in this one let’s add reset state that we have already created to display the score we have to call this reset function and instead of question we have to display the score so we are displaying the question in the question element so in this one we will add inner HTML and let’s add the text in backtick here we will add us code so it will display the escore out of the length of question and after that we will add next button dot inard HTML equal to play again and uh next button will be block so let’s add next button do style do display block after adding this let’s come back to the website again and let’s select the correct answer next again correct answer next again we will click here next and here next you can see us code four out of four and we are getting the button play play again it will restart the quiz let’s click the wrong answer it will display the correct one let’s click next and wrong answer so we have selected two wrong answers let’s click again click here it is also wrong and if we click here on the correct one so you can see the score one out of four because we have selected only one correct answer out of four and we are getting play again so finally this quiz app is working you can update your question in this JavaScript and you can create your own quiz app or quiz website using HTML CSS and JavaScript in this video we are going to learn how to add the validation in contact form using JavaScript so here you can see I have created a contact form where you can see the input field for the name phone number email ID and message and at the end we have the submit button if I click on the submit button you can see it is giving an error name is required and there was one more error message at the bottom called please fix error to submit first we have to fix the error which is in the name field so here we have to enter the name because right now the name field is empty so let’s add anything here if I write like this still we are getting an error write full name because we have to add the first and last name so let’s add a space and write full name like this now you can see a green check icon that means this input field is correct so after adding the correct data in this name input field let’s click on the submit button again so it is giving error in the phone number field and here it is saying phone number is required so let’s add some characters here if I write like this it is saying phone number should be 10 digits so let’s add any 10 digit number here so so now you can see check mark it means this input field is correct after that if I click on the submit button again it is giving an error in email field so here also we have to add the email ID so let’s add the email ID like this so right now this is not the correct format so that’s why it is saying email invalid so we have to add the email in proper email format so if I write like this now you can see a check mark let’s click on the submit button again and it is giving an error 30 more characters required because we have added the limit minimum 30 colors should be there in the message box so here let’s add any message you can see as I’m writing the text here it is decreasing the required character right now it is saying 16 more characters required after writing minimum 30 characters in this message field we will get this check mark now we can submit this form so let’s click here and you can see it will submit the form so without collecting all the fields this form will not be submitted and once we will collect all the input fields and click on submit button this form will work so we will learn how to add this validation in form using JavaScript now let’s start this tutorial to add validation on contact form using JavaScript I have already already created multiple tutorials about creating a contact form using HTML and CSS that’s why in this video I’m not going to design this form you can go to the video description and download this HTML and CSS form and in this video we will only talk about the validation so let’s come back to the folder and here you can see I have this HTML and CSS file that you can also download from the video description once you will open these files with the code editor you will see this HTML file where I have added the container and then we have the form tag and in this form we have added this icon and here we have added the font awesome link that’s why we have added this font awesome icon then we have the input group and in this one we have the input field for the name this is for the phone number this is for the email and this one is for the text box and after that we have the button and you will get this CSS file also where we have added all the CSS for the design of the form once you will open this HTML file with B browser you will get this form like this next we will display the error message on this form so let’s come back to the code and here you can see we have added the input field for the name so just below this input field we will add one span tag and in this span let’s add one ID also so I will add the ID name error and in this name error let’s add a error name is required like this simply we will add the span tag in all the input group just below the input field so here also we will add this fan tag and this is for the phone number so we will add the ID phone error and here also one message phone is required let’s copy this one and add it just after this input field for the email here we will add the ID email error and we will add the message email is required and uh after that we will add one span here this is for the message error message is required like this and uh we will add one message after this submit button also so here also we will add a span and we will add the ID submit error and one message please fix error so we have added these error message in this HTML file and let’s refresh our website and now you can see these message here at the end of all the input fields and one error message at the bottom left corner of this form so we have to change the position and color for these error message for that we will come back to the HTML file and here you can see we have the class name called input group and in this input group we have the span tag where we have added the error message so let’s add this class name in the CSS file and here we will add the span and for this aspan we have to set the position Position will be absolute then we will add the bottom bottom will be 12 pixel and right 17 pixel we will add the font size it will be 14 pixel and color so the color will be red because it’s an error so you can see the position has been changed for these error message we have to add the Cs for this one also which is for the submit error let’s come back and here you can see we have added the ID called submit error so let’s copy this ID write it here with the hashtag because it is an ID and here we will add color red that’s it so this message is also in the red color so we have added the position and color for the error message but right now this message is displaying by default but we have to display this message after validation using JavaScript so we will remove these error messages for now and it will be displayed later let’s come back and come to the HTML file and just remove this message span tag will be there we have to remove the message only let’s remove all the error message like this it’s done again you can see the simple contact form now we have to add the JavaScript file so here we will create a new file go to files new file and uh save this file as uh script.js make sure the file name should be JS so we have created a new file and uh next we have to come to the HTML file and just at the bottom before this closing body tag we will add a script a script open and closing tag write SRC and write the file name that we have just created which is script.js so it will connect the Javascript file with the HTML file next we have to add the variable for all these ID that we have written here in this HTML file so let’s come to the script file this is the script.js and here we will create variable so let’s add where name error equal to document dot get element by ID and in this ID we will add the ID that we have added in the HTML file so you can see we have added the ID called name error just copy this one and place it here so this is the first variable just duplicate this one and change the name it will be phone error this is for the email error this is message error and this one for the submit error and here also we will change the ID so we have added these variables next we have to add the function that will validate the input box so let’s come back to the stml file and here we have the input field for the name in this one we will add one ID so let’s add one ID called contact name and we will add one event so it is on key up on key up equal to and here we will add one function name so let’s add any function name validate name like this so here we have added one ID and one function next we have to Define this function that we have added here so just copy this function and come to the script file here we will add function write the function name like this so this function will be executed whenever we will start typing anything in the input field so here we will add one variable and write name equal to document Dot get element by ID and in this ID we will add the ID that we have just created which is contact name copy this one add it here at the end we will add dot value so this variable called name Will store the content written in the input box which is for the name so it will take the value of the input field and now we will add the condition so here we will add if name Dot this will check whether this name length is zero it means the input field is empty so it will display an error called name is required and where this error message will be displayed it will be displayed in the variable called name error and this name error is for the ID called name error that we have added here in this span tag so in this span tag we will see this message called name is required when the length is zero it means the input box is empty next we will add the another condition here we are adding this condition so this expression is exactly checking the first character should be alphabet and after that there will be one space and after that it could be any character A to Z here we are adding exclamation it means value is not matching with this expression then it will give an error so what will be the error just copy this one paste it here and here we will add write full name like this and one more thing once it will give an error it will return false like this and we will add this return false in this if condition also so whenever there will be an error it will return false in this condition also if it will give an error it will return false if there is no error then what will happen it will display a success message so let’s add name error dot inner HTML equal to and in this one let’s add valid like this Suppose there is no no error then it will say valid and then it will return true like this it is not and it will be a dollar sign like this so again refresh the website and you can see if I write a first name and write anything in the second name it will say valid you you can see the message has been changed to valid so instead of valid we want to display a check sign so you can see in the HTML file we have added this font awesome link so we can add the font awesome icons so let’s come to the font awesome website here we will search for one icon so let’s go to the icon and search for check we’ll click on this one check Circle copy this and come back to the script file and in this script instead of this valid we will add this HTML code like this and we will change the color also so it is in the it tag you can see it is in the it tag so we have to use this it tag in the CSS file just come to the CSS and copy this input group span and uh in this Supan we have the it tag for the icon and here we will add the color so let’s add the color of this one after adding this color come to the web page and here we will add one name now you can see a green color of check sign so it is working fine next we will add the validation for the phone number field so let’s come back again come to the HTML file and as you can see we have added the ID in the name field and one function so same thing we will do in the phone number field so just copy it here so this is for the phone number field so it will be contact phone ID is contact phone and here we will add validate phone like this come to the script file and let’s copy this one paste it here instead of validate name we will add validate phone this is for the phone number validation and again we have to add the variable so let me just copy this one only paste it here it will be phone equal to document. G by ID contact phone ID is contact phone so this phone will store the value written in the phone number input field next we have to add the condition to check the phone number so here let me write the condition then I will explain to you so you can see here we have added phone. length equal to Z so it will check whether the phone number field is empty then it will display and eror phone number is required next it will check the length of the phone number if it is not equal to 10 then it will display an error phone number should be 10 digits in this condition it is checking the phone num should be 0 to9 and for 10 characters and if it is not like that then it will display an error called only digits and if there is no error like this then it will display a check icon and it will return true so after adding this let’s check the phone number field come back to the web page and here if I write you can see phone number should be 10 digits so let’s add more digits and now you can see a check icon you can see if I add any character like this Zed y anything it is saying only digits please so we need to add digits and if we add 10 digits it is fine so this phone number validation is also working now let’s come back and we will add the validation in this email field so let me just copy this one and paste it here in this email input field write the ID contact email and this is validate email next we will add the script so let’s copy this one it will be validate email then copy this paste it here it will be email document. get elment by ID contact email so it will store the value written in the email input field and now we will check the conditions for so in this validate email function we are adding this variable that will get the value of the input box and then it will check the length if it is zero it means it is empty so it will display an error email is required and return false next if there is some value then it will check this condition and here it is saying it should be any alphabet it may contain a DOT or underscore or the siphon and it can also contain any number and after that there should be one at theate after at theate there will be some alphabets and then one dot and after that dot there will be another alphabet it could be 2 three or four characters so if the email format is not matching with this one then it will display an error called email invalid and return false and if there is no such error then it will display the check icon and return true here we will remove this and save this file let’s refresh the website again and if I write uh correct email here now you can see it is displaying a check icon it means the email ID is valid next we have to add the validation for the message box let’s come back and here we will add one ID and one function copy and paste it here write the ID called Contact message and this is validate message now let’s come back to the script file and copy this one here we will add validate message and in this one again we will add one variable so it will store the value written in the message box and after that we will add one variable where we will add any number required equal to so if we want 30 characters then we will add 30 characters is required and here let’s add another variable and it is left left equal to required minus message do length so it will give the value how much characters is left and now we will add the condition if left greater than zero it will be giving an error message message error dot inard HTML and then it will return false and if there is no such error and the character is more than 30 then it will display a check sign just copy this one paste it here and here we will add message error. innerhtml that’s it here it will be this one message refresh the website and now you can see if I write something 29 more characters required if I delete this one it will display 30 more characters required and if we write some text here and now you can see the error message has gone and we will get the check icon so this message box validation is also working fine next we have to add the validation when we will click the submit button so let’s come back in this button we will add onclick and here let’s add return space and one function validate form next we have to Define this function called validate form in the JavaScript so let’s copy this one come back to the Javascript file and here we will add a function validate form and in this one first it will check all the functions that we have added in the different input field so here we will add if exclamation validate name then we will add exclamation validate phone in the series wise we are adding so this condition we check if any of these are false then it will display an error message so here we will add submit error dot inner HTML and one message like this and after that it will also return false after adding this again refresh the website and simply click on the submit button and you can see here it is displaying please fix error to submit so M submit but right now this error message will be displayed continuously so we have to hide this message after a few seconds so let’s come back and here we will add submit error dot style do display it will be block so it will be visible and here we will add set timeout display none so after 3 second it it will hide the error message which is please fix error to submit so this message will be displayed for 3 second and after 3 second it will be hidden because we are adding display none in the set timeout and it will return false so it will not submit the form so let’s check this one and if I click here you can see this message will be hidden after some time you can see this message is hidden so this complete form is working fine right now let me check check all these input field and if I write a name here then we will add one phone number and any email ID and message after collecting all the input field if I click on sub MIT it will submit the form successfully without any error message so it is working fine so we have completed this form validation using JavaScript in this video we are going to learn how to create an image gallery that will slide horizontally using Mouse wheel usually when we rotate the mouse wheel the web page scroll down or a scroll up but if I take cursor over this image gallery and rotate the mouse wheel it will scroll the gallery horizontally either in the left side or right side in this image gallery we have added two control icons also that is for the backward and forward we can click on these icons to scroll the gallery to the left side or right side we have added one more effect if I take cursor over this image you can see the image becomes colorful all the images are gray right now when we take cursor it becomes colorful and you can see the image size is also increasing when we take cursor so we will create this horizontal scroll with mouse wheel using HTML CSS and very simple JavaScript this will be very good JavaScript mini project for your resume now let’s start the video here I have this folder and in this folder I have one HTML file one CSS file and another folder called images and here you can see some images and two icons you can find all these images download link in the video description now I will open these files with my code editor which is Visual Studio code so this is the HTML file where I have added the basic HTML structure and this one is the CSS file in this HTML file I have added this title then this link tag that will connect the CSS file now we will add the code within this body tag so here we will create one div with the class name gallery and within this Gallery we will create another div and in this div we will add span and inside this span we will add the first image with the IMG tag here we will add the file path of the image it is images / image1.png Let’s duplicate this line and we will add the another image image 2 and three after that let me open this web page with browser so you can see three images on this web page now let’s come back and here we will copy this class name and come back to the CSS file here first we will add the Cs for the body and here in this body we will add the background after that add that class name Gallery here we will add the width it will be 900 pixel and display Flex after that we will add gallery and div for this div let’s add the width of 100% display grid and grid template column Auto auto auto so we will get three image in one row after that we will add grid gap of 20 pixel and padding of 10 pixel then we have the IMG tag so here we will add gallery div and IMG width will be 100% for the image now you can see perfect size for these images next we will add three more images so let’s come back and duplicate this div and replace the image file name it is 456 so we have total six images you can see the images size becomes small so let’s come back and here we will add Flex none now you can see it is perfect size for the image and you can see the horizontal scrolling here the complete website is scrolling so let’s come back and uh here in this Gallery we have to add overflow X scroll now only this Gallery will scroll the gallery width is 900 pixel and it is scrolling inside that div next we have to hide this horizontal scroll bar so let’s come back and here we will add gallery and webkit scroll bar display none so that horizontal scroll bar is hidden but we cannot scroll it with the mouse wheel so let’s come back and uh Above This Gallery we will add another div with the class name Gallery WAP and in this one we will add one image and file name back do PNG then another file name next. PNG here we will add ID back BTN and next vtn and let’s remove it and add it here within these images so first we have the back arrow then all images and again next Arrow you can see the back arrow at the top and the next Arrow at the bottom here we will add gallery W display Flex align item Center and justify content Center then we will add the margin of 10% Auto you can see it is horizontally centered now just come back and copy this ID back vtn then next vdn we are adding hashtag because it’s an ID here we will add the width 50 pixel cursor pointer and margin 40 pixel now the size for the icons are perfect next we will add the hover effect on these images so let’s come back and here we will add gallery div IMG and hover and uh let’s add filter gray SK zero the G scale will be zero and come here and we will add cursor pointer and transform scale 1.1 so it will increase the size just copy this filter gray scale and add it here and let’s add 100% so the default gray scale will be 100% so the image will be gray let’s add the transition transform 0.5 seconds so it will take5 seconds to increase the size you can see the size is increasing and the image becomes colorful when we take cursor so we have added the hover effect after that we have to enable the horizontal scroll using Mouse wheel so just come back and here above this closing body tag we will add a script tag in this script tag we will add the JavaScript so here we will add let scroll container equal to document dot query select and we will select this one do Gallery so we are selecting this class name after that we will add let back vtn equal to document. get element by ID because we have the ID here back vtn so write it here now duplicate this line and it will be next vtn so we have selected the gallery div then next vtn and back vtn after that let’s call copy this one add it here here we will add add event listener and it will be wheel so it is wheel event then we will add this Arrow function and when we will rotate the wheel this function will be executed so here we will add EVT do prevent default it will prevent the default feature that scroll the web page down or up next we will add the scroll container scroll left plus equal to EVT dot Delta y after that come back to the website and if I take cursor over this image and rotate the mouse wheel this slider is scrolling we can scroll in the left direction or right direction you can see this image gallery is scrolling horizontally with the mouse field now we will add the click feature on this back arrow and next Arrow so let’s come back and hit we will add next BTN do event listener click because we will add the click function here also we will add the arrow function and this function will be executed when we will click on the icon here we will add scroll container do scroll left plus equal to 900 because the width is 900 for the gallery again duplicate it and here we will add back BTN and it will be minus equal to 900 that’s it after that let’s come back and if I click on the back button it is a scrolling the gallery to the left side and if I click on the right button it is a scrolling the gallery to the right side but when we click on these icons it immediately scroll it by 900 that’s why we cannot see the scroll animation so let’s come back and here we will add scroll container dot Style dot scroll behavior and we will add the scroll Behavior smooth let’s copy it and paste it here same thing now just come back and if I click here you can see it will scroll smoothly you can see this Gallery is scrolling horizontally when we click on these next or previous button and we can scroll it using the mouse wheel also but you can see this mouse wheel scroll is not smooth right now so let’s come back and uh here copy and paste it in this V event and here we will add Auto that’s it after adding this let’s come back now if we rotate the mouse wheel this Gallery is scrolling smoothly and when we click on the icon here also it is scrolling smoothly and we have the hover effect also so finally we have completed this beautiful image gallery that scroll horizontally using the mouse wheel in this video we will learn to make a digital clock using JavaScript let’s check the current time in my laptop at the bottom right corner so the time is exactly same as the time displaying on my website we will Design This digital clock using HTML and CSS then we will update the local time using JavaScript this is very useful JavaScript project for your job portfolio so let’s start to make this digital clock using JavaScript a step by step here I have this folder and in this folder I have added one index.html file one style. CSS file let me open these files with my code editor which is Visual Studio code you can use any code editor so this is the HTML file where I have added the basic HTML structure and this one is the CSS file where I have added the margin padding font family and box sizing these CSS properties are applicable for all the HTML elements in this HTML file I have added this title digital clock using JavaScript e tutorials and then I have added this link tag that will connect the HTML and CSS file because here I have added hdf style.css now we will add the code within the body tag so so here let’s create one div with the class name hero and now we will add the CSS for this class name write this class name here in this CSS file and here we will add the width height main height will be 100 VH then we will add the background and in this background we will add the linear gradient color here we will add one angle and two color code then we will add the color this will be the white color and let’s add the position relative after adding this let me come back to the folder and open this HTML file with any web browser so you can see this gradient color on the complete web page let me close this browser and I will open it with the visual studio code extension called live server so that it will refresh the web page automatically whenever we will add any changes in the code file and save the code file so you can see the same web page again with the gradient color now let’s come back and within this div with the class name hero here we will create another di with the class name container inside this container we will create another with the class name clock and in this clock let’s add the time like this save this and open the web page you can see this time here at the top left corner 0 so let’s add some CSS let’s come back and here we have the class name container just add it here in this CSS file and here we will add the CSS for this content container we will add the width it will be 800 pixel and then we will add the height height will be 180 pixel after that we will add the position absolute top 50% left 50% and transform translate – 50% and – 50% so that this element will be in the center of the web page for now here we will add one background so let’s add the background red and open the web page so you can see this red color of box in the center of the web page now we’ll remove this color let’s come back to the HTML file and here we have the class name clock so let’s add the CSS for this clock here we will add the width and height 100% after that we will add the background and in the background we will add some color with less opacity so we will add rgba so this is the color code for the background then we will add the Border radius of 10 pixel and uh let’s add display Flex align items Center and justify content Center so that the text inside this clock will be in the center and after that come back to the web page you can see this color in this box now we will add two other elements that is a square and circle so let’s come back we will add the element with the help of cudio elements so here in this container we will add two cudio elements which which is before and after so add this container then write double column before and in this before we will add content content will be empty then let’s add the width and height width will be 180 pixel and height also same 180 pixel then we will add the background here we will add one color code then border radius will be 5 pixel very small and Position will be absolute left Min – 50 pixel and top also Min – 50 pixel then right Z index minus one after adding this you can see one element at the top left side of this horizontal box now we will create another element that that will be one Circle so let’s come back and duplicate this one here we will add after this is same content width height and we will change the background color and here we will add border radius of 50% so that it will be a circle Position will be absolute and here it will be on right side so right minus 30 pixel and it will be at the bottom so write bottom minus 50 pixel that’s it now you can see one Circle in the right side next we have to make this horizontal box blur so let’s come back and here we have the clock so in this clock we will add backdrop filter blood it will be 40 pixel after that you can see the web page it looks good next we have to change the size for this text and we will add the name also like minutes second hours so let’s come back and uh here let’s remove this one instead of writing the text directly we will add one span tag and in this span first we will add 0 0 Let’s duplicate it here we will add the column after updating this you can see again it is same we have just added the span tag for each number let’s come back here we have the span inside this clock so come to the CSS file let’s add dot clock and a span so for each a span we will increase the font size so let’s add the font size 80 pixel we will add the width 11 10 pixel and uh display will be inline block and text align Center and P relative after that you can see some space between these numbers and the font size is also increased next we will add the name like hours minutes and seconds so let’s come back to the code again and let’s copy this clock span and write the sudo element after and this after let’s add the content in this content it will be empty font size 16 pixel position absolute bottom – 5 pixel and left 50% transform translate x – 50% in this content we can add the text so let’s add ours it will be 16 pixel PX and after applying this you can see we have the text here hours hours hours like this and we have to remove this hours and it will be different in the first one we will add hours then minutes and seconds to change this one we will come back to the the HTML file and in this HTML file let’s add some IDs in the first span we will add the ID HRS for the RS then in the second number here we will add ID Min n that is for minutes and in the last one we will add the ID SEC for the seconds and let’s come back to the CSS file and remove this content from here remove this and here at the end we will add that ID like HRS and here we will add sudo element after write content ours duplicate this line it will be minute and second and here also minutes and seconds after adding this let’s come back to the website so you can see in the first number we are getting hours then in the second one minutes and last one seconds next we have to update the time and uh to add the current time we need to add the JavaScript so let’s come back to the HTML file and here at the bottom just above this closing body tag we will add a script open and closing tag and within this script we will add all our JavaScript code so here we will add let HRS equal to document. getet element by ID and the ID is HRS that is from here let’s duplicate it it will be minute and second to get the date and time we need to use the JavaScript object called date so here let’s add let current time equal to new date and if we print this current time let’s add console.log current time you will see the local time and date let’s come back to the website and open the console here you can see it is displaying Tuesday May 30 2013 and this is the time so it is our local time now we have to get the time only we have to remove the date and day so let’s come back here you can use the JavaScript methods get hours get minutes and get seconds to get the hours minutes and seconds from this time so let me show you here we will add current time dot get ours and open the web page you can see it is displaying the hours 15 if we come back and add get minutes it will display the minutes in current time 37 and like that we can get the seconds also so let’s display all those things here we will add HRS do inner HTML equal to current time dot get hours so it will display the hours of current time duplicate this it will be minutes Min and it will be seconds second and here also we will update the methods get minutes and another method called get seconds so after updating this let’s come back to the website you can see the current time here which is 15 38 and 39 let me show you my laptop current time it is same 1538 but you can see this time is not updating so we have to update it it at every second for that we will use the set interval so let’s come back and we will add all those things in a set interval here we will add comma 1000 milliseconds that means 1 second and and within this we will add all these code so it will execute this code at every 1 second now just come back to the website again and you can see this seconds is increasing and this minute is also increasing right now it is displaying only one digit so suppose you have the numbers less than 10 we can add one zero in front of that number for that let’s come back to the JavaScript again and here we will add one if condition so we will add the inline if condition copy this and here we will add plus this one and here we will add the condition if less than 10 if it is less than 10 then it will add one zero or if it is not less than 10 then it will be empty like this so we have to add the same thing in the other one here and here and update the methods it will be minutes minutes and seconds after updating this let’s come back to the website again and finally you can see it will display the double digit in the numbers now you will see it is starting from 0 1 02 03 like that so finally we have completed our digital clock using HTML CSS and jav JavaScript in this video we will create a product page design that you can use on e-commerce website here I have added a product image on the left side and product details on the right side in this product image we have some control buttons when I click here you can see the product image is changing in the product detail section you can see the product name price and offer after after that we have some select option for variable products we can select the size and color of the product then we have input field to select the product quantity and at the bottom you can see by now button we will create this product page design using HTML CSS and JavaScript here in this folder I have created one index.html file one style. CSS file and you can see another folder with some images you can find all the images download link in the video description let me open these files with my code editor which is Visual Studio code you can use any code editor so this is the HTML file where I have added basic HTML structures and this one is the CSS file and I have connected this CSS file with this link tag in the HTML file now we will add code in the body tag so here we will create one dip with the class name container in this container we will create another div and let’s add the class name product in this product we have to create two columns so first we will create the left TI with the class name Gallery where we will add the product image gallery and let’s add another div with the class name details where we will add the product details like product title description and buttons next we will add the image in the first div which is image gallery so here we will add one IMG tag write the file path of the image so this is the images / image 1.png after adding this let’s come back to the folder and open our HTML file with any web browser so you can see this image on the web page let me close this browser and I will open this browser with the visual studio code extension called live server so that it will refresh the web page automatically whenever we will add any changes in the code file and save the code file so you can see the same B page page again now let’s come back and we will add the CSS so let’s copy this container write it here in the CSS file here we will add some CSS properties like width then we will add Min height then we will add the background in this background we will add one color code let’s add the display Flex align items Center justify content Center so that the product will be in the center of the web page let’s copy this class name product write it here so for this product we will add the width it will be 90% and maximum width will be 750 pixel then we will add display Flex so left and right column will be side by side now we will add the CSS for this gallery and details so let’s add this Gallery here so for this Gallery we will add Flex basis 47% it means width is 47% after that we will add the background so this is the color code now in this Gallery we have one image so again write this one then write IMG tag so for this image we will add the width it will be 100% and display it will be block let’s add some padding from the top 100 pixel and after adding this again refresh the website you can see this image on the web page next we will add the CSS for the right column which is details so here we have details just copy this one write it here in this CSS file so for this one we will add the flex bases 53% it is width 53% so now we will add the background it is white and we will add some padding it is 40 pixel and let’s add the padding from left side it will be 60 pixel now you can see this white color in the right side and in the left side you can see this image now we have to increase the size for the left one so here in this Gallery we will add transform scale 1.08 so it will increase the size let’s add the Box Shadow also so here we will add box Shadow next we will add the same box shadow in the second column which is details so just copy this one and paste it here after adding this let’s come back to the website again you can see the size for the left column is increased and you can see the shadow also now we will add some details in the second column so here in this second div we will add space and here we will add one title in H1 it will be the name of the product casual t-shirt next we will add another text in H2 so it will be the price of the product again we will add H3 and here let’s add the discount 30% off after that we will add some description in P tag so this is the description after adding this you can see this title and description on the web page so we have to design these things so just copy this class name details WR it here and here in this details we have the first title in H1 so for this H1 we will add this color code and we will add the font size you can see different size for this text again write this class name then write H2 for the second Title Here we will add another color and font size it will be 30 pixel and we will also change the font weight 600 let’s add this class name again and here we will add H3 for the discount so in this one we will add color and margin from the bottom to add some space at the bottom so you can see these titles looks good next we will add the CSS for this description for that we will come back back and here in this details here only we will add font size it will be 13 pixel and we will change the font weight let’s add the color after adding this this description is also looking good next we have to add some radio buttons where we can select the size and color so let’s come back and after this P we will add one form tag and in this form we will add one div so let’s add the div with the size select and in this size select first we have to add one text in P tag it is size then we will add one label in this label we have to add the four it will be small and inside this label we will add one input field so in this input field input type will be radio so it will be a radio button then we will add the name let’s add size and in this ID we will add the same thing which is here for this ID and for should be shame after that we will add a span and in this span we will add s s means small let’s duplicate this label and change the ID and for so this will be medium and here also medium this will be M duplicate again and write large and ID also large and a span L again we will add this one then right extra large for Excel let’s duplicate again and this is the last option dou x large double XL after adding this again refresh the website you can see this text size then we have the radio buttons for SML Xcel and double XEL you can select these radio buttons now let’s come back to design this one we will copy this form here we will add details form so for this form we will add the font size it will be 15 pixel then we will add the font weight then we have the size select so let’s copy this one write it here size select in this one we will add display Flex so that the text and radio buttons will be in the same horizontal line aligned items will be Center and some margin from the top to add some space again copy this one here we will add P so for this P tag we will add the width it will be 70 pixel now you can see this size here then we have some space and after that these radio buttons and text next we have to change the color of these text which is SM L XL so let’s come back and copy this one here we will add input then checked so if the input is checked we have to change the color of the span text so here we will add plus span and color we will add this blue color and we will also increase the font weight it is 600 so you can see when I select any radio button the color for the label text is changing and the font weight is also changing next we have to hide these radio buttons there will be only text copy this size select input and just add display none so it will be hidden you can see we have only text here and we can click over these text to select any radio button that is invisible so again come back here we will add site select then a span so for this span we have to add some space so first we will add some padding then margin from the right side and we will add the cursor pointer so it looks good and we can click on any text to select this one and the color and font weight is changing when we select any size so we have completed this size select let’s come back and after closing of this div which is for the size select or you can add it here just above this closing form tag here we will add one div with the class name color select where we will add radio buttons to select the color so in this one again we will add text in P tag it is color then we will add label for let’s add red color and in this for again we will add input input type will be radio then we will add name in this name we will add color and let’s add the ID red for and this ID should be same after that again we have to add one span and in this span we will add one class name so it is color one after adding this let’s duplicate this complete label total we have four colors so let’s change the color it is green and here also green and in this span we will add the class name color two now for the third one we will add blue and ID also blue this is color three now for the fourth we will add for pink ID pink and class name color four after adding this let’s refresh the website again you can see this color and then we have four radio buttons now we have to align all these in same horizontal line so again come back let’s copy this class name color select write it here in the CSS file and for this color select we will add display Flex then align items Center and some space from the top again WR this class name and in this one we have P tag so we will add width 75 pixel you can see it is in the same horizontal line we have some space after this color next we have to add different color with the each radio buttons so let’s come back and in this CSS file we will add this class name again then write span so for this span let’s add display it will be inline block then we will add width and height it will be 15 pixel after that we will add border radius it will be 50% so that it will be a circle after that we will add some spad so we will add margin right 15 pixel and cursor will be pointer now we have to add different color in each as span so we have added class name color 1 2 3 4 so for all these span we will add different color so here we will add color one and write background it will be R let’s duplicate it and we will change the class name color 2 3 4 and for all these class name we will add different color now we have added different background in all the span again refresh the website and here you can see we have different color circle with the each radio buttons next we will hide these radio buttons only color will be visual so let’s come back and copy this class name color select then input here we will add display none that’s it so it will be hidden you can see we have colors here now we have to select the color so let’s come back and here we will add color select input checked so whenever the input button is checked we will Design the span so here we will add plus a span transform scale 0.7 so it will reduce this size size then we will add box shadow in this Shadow we will add two Shadow this will be in the white color and again we will add the same thing let’s add a comma and write another Shadow so here we will add black color and it will be 6 pixel so after adding this again refresh the website and you can see see when we click on any color there is one circle around it so this select option is working next we will come back to the HTML file and here before this closing form tag here we will create another div with the class name quantity select inside this div we will add one title in ptag it is quantity and again we will add one input field and input type will be number and value it will be one after adding this let’s refresh the website you can see this quantity and this input field with the value one and we can increase and decrease this value with these Arrow let’s come back and copy this class name quantity select write it here in the CSS file here again we will add display Flex align items Center and some space so margin top 20 pixel WR this class name again then write p and for this P we will add width it will be 75 pixel you can see it is in the same horizontal line next we will Design This input field let’s come back and here we will add quantity select input so for this input field we will add the background this is the color code for the background then we will add border it will be zero and outline it will be zero let’s add some padding inside this input field then we will add width it will be 50 pixel and B radius it will be 12 pixel you can see this input field looks good we can increase and decrease the value by clicking on this up and down buttons after adding these input fields we will add one submit button or a buy button let’s come back and just above this closing form tag we will add one button and button text will be by now you can see this button here next we will Design This so let’s come back to the CSS file here we will add form button in this button we will add the background this color code then we have to change the button text color after that increase the font size of this button text then width it will be 100% and some padding it is 10 pixel and Border radius will be 30 pixel after that we will add border zero and outline Z then we will add margin from the top to add some space from the top and box Shadow here we will add this box shadow then cursor pointer after adding this again refresh the website and you can see this button looks good so we have added all the contents in the product detail section now we will add controls option in the gallery where we will click and change the gallery image so let’s come back and in this Gallery after this image we will add one div with the class name controls inside this div we will add three asan and with this span we will add the class name BTN just duplicate it so we have three span here with the class name BTN next we have to design this one so copy this class name controls write it here in this CSS file here we will add position Position will be absolute then bottom it will be 40 pixel and right it will be 20 pixel so this control buttons will be in the bottom right side of the gallery here we will add BTN so for this span we will add display block and we will add the width and height 10 pixel then we will add border radius 50% so that it will be one small circle then we will add the background so in this background we will add the color code in RGV it will be white colored with 50% opacity then we will add some margin and cursor it will be pointer so here in this controls we have added position absolute so we will add position relative in this gallery you can see we have added Gallery over here at the top so in this one we will add position relative so this control buttons will be in the gallery only after adding this position relative again refresh the website and you can see these three Circle in this product Gallery next we have to add one color in the first one so it will look active so let’s come back and here in this first button we will add one one more class name active after adding this let’s come back to the CSS file at the bottom we will add BTN do active and here just we will change the color let’s add the background and this color code after adding this again refresh the website you can see this blue color in the first dot next we have to add the click function whenever we will click on any other dot the image should change so for that we will add the JavaScript so let’s come back and here in this HTML file we have to add the click feature on this span where we have added class name BTN and we will change the image in this IMG tag so here in this IMG tag we will add one ID also so let’s add the ID product IMG after adding this let’s come back at the bottom just above the closing body tag here we will add a script tag where we will add the JavaScript inside this we will add let product IMG equal to document. get element by ID and you already know the ID which is product IMG next we will add the let BTN equal to document Dot get Elements by class name because we have added the class name BTN in all the span after that we have to add the click feature on the button so here we will add BTN 0. on click equal to function and inside this function we will add the product img.src because we have to change the image so let’s add product img.src equal to the file path of the image so let’s come back to our folder you can see we have one folder called images and inside this folder we have the image called image 1.png 2.png and image 3.png so this is our file path so let’s come back and here we will add images SL image 1 do PNG so this is the first image after adding this let’s duplicate this one and here we will add BTN 1 and BTN 2 for the second button and third button and we will change the image also it is image 2.png and image 3.png after adding this let’s refresh the website again and if I click on the second button you can see the image is changing if I click on the third one image is changing right now the image is changing when we click on these dot but the color is not changing for the dot which is active so we have to change this one we have to change the active color for the circle so let’s come back and here we have added the class name active so we have to remove this class name through JavaScript and this class name will be added in the particular Circle where we will click to remove remve this one we will add for BT of BTN bt. classlist do remove and inside this remove we will add the class name which is active so it will remove the active class name from all the circles so after removing the class name we have to add this class name on the particular Circle where we have clicked for that here we will add this do class list do add and the class name which is active so first it is removing the class name from all the circle and adding the class name on the particular Circle let me copy this one and add it in all the function just copy and paste in the second and third one that’s it again refresh the website and you can see if I click on any Circle the image is changing and the color is also changing when we click on the second one the second Circle becomes blue when we click on the third one then third circle becomes blue so finally we have created this image gallery and product description for this product page I hope this JavaScript course will be helpful for you if you have any question you can ask me in the comment section please like and share this tutorial and also subscribe my channel greatest Tech to watch more videos like this one thank you so much for watching this video
Affiliate Disclosure: This blog may contain affiliate links, which means I may earn a small commission if you click on the link and make a purchase. This comes at no additional cost to you. I only recommend products or services that I believe will add value to my readers. Your support helps keep this blog running and allows me to continue providing you with quality content. Thank you for your support!