Week 12 Javascript Foundation Week 12 Javascript Foundation Why languages? Interpreted vs compiled languages Why JS >> Other languages in some use-cases Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, strings, booleans) Complex primitives in JS (arrays, objects) Functions in Javascript Practise problem solving Callback functions, Event loop, callback queue, Asynchronous programming Callback hell and Promises Why languages? RAM vs ROM vs SSD vs HDD: RAM, ROM, SSD, and HDD are all types of computer memory/storage but serve different purposes and have distinct characteristics: ### RAM (Random Access Memory): - **Purpose:** RAM is volatile memory used for temporary data storage while a computer is running. It holds data that the CPU needs to access quickly for ongoing operations. - **Characteristics:** - Fast access speed: It's much faster than other types of storage like HDD or SSD. - Volatile: Data is lost when the computer is powered off. - Usually smaller in capacity compared to storage drives. ### ROM (Read-Only Memory): - **Purpose:** ROM stores firmware and essential instructions for booting up a computer or device. - **Characteristics:** - Non-volatile: Data remains intact even when the device is powered off. - Cannot be easily modified: It typically contains permanent instructions or firmware. Computer RAM SSD Why languages? Interpreted vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, strin Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Why languages? Scripting vs compiled languages Why JS >> Other languages in some us Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, string Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callbac Callback hell and Promises Why languages? Computer RAM SSD In SSD we have all our storage of apps/photos/videos and all while in RAM is a place where whatever you are currently running app runs. Initially the app was stored in SSD and once you click it then it will start running in RAM as well. Whenever you execute anything in your machine it goes into your RAM as 0s and 1s(not any source code or C++ program). But the application code is written in C, C++, Java, etc and all these are high-level languages and there are compilers for these languages which convert this code in 0s and 1s and finally these 0s and 1s go into the RAM. Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, strin Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Why languages? Computer Statically present on machine RAM ### SSD (Solid State Drive): - **Purpose:** SSDs are storage drives used to store data persistently. - **Characteristics:** - Faster than HDDs: SSDs have faster read/write speeds than traditional HDDs. - Non-mechanical: SSDs use flash memory (non-volatile memory) and have no moving parts, resulting in faster access times and better durability. - More expensive per GB compared to HDDs. ### HDD (Hard Disk Drive): - **Purpose:** HDDs are traditional storage devices used for storing data. - **Characteristics:** - Slower than SSDs: HDDs have slower read/write speeds compared to SSDs. - Mechanical: They use spinning disks and mechanical arms to read/write data, making them slower but generally more affordable for larger capacities. - More susceptible to damage from physical shock due to their mechanical nature. SSD Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, strin Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Why languages? Open/double click 0100100 0010100 1010101 Computer Executing on machine ### Comparison: - **Speed:** RAM is the fastest among these memory types, followed by SSDs, while HDDs are the slowest. - **Volatility:** RAM is volatile (data lost when powered off), while ROM, SSDs and HDDs are non-volatile (data remains when powered off). - **Usage:** RAM is used for active data storage during computation, ROM for permanent firmware, SSDs for fast and persistent storage, and HDDs for larger but slower storage. Each type of memory/storage serves specific functions, and computers often use a combination of these technologies to balance performance, capacity, and cost. RAM SSD // example.cpp #include <iostream> int main() { std::cout << "Hello, world!" << std::endl; return 0; } Why languages? This file is a plain text file written by some developer. When you save this file to your computer's disk, the file system stores its content in binary form. Each character in the file (including letters, symbols, and whitespace) is represented by one or more bytes according to the chosen character encoding (e.g., ASCII, UTF-8). For instance, the letter 'H' might be represented by the byte value 72 in ASCII or 0x48 in hexadecimal notation. But in this code there is no info like we have to print "Hello World" on the screen. Now when we compile this code using a compiler it creates a binary executable file which has instructions and all in 0s and 1s format for the machine stating that it has to print "Hello World". Computer Hence even if we store this cpp file in 0s and 1s in the memory still we need compiler, because compiler creates another file from this which actually needs to get executed. RAM SSD Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, strin Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, strin Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Why languages? Computer RAM SSD 0100100 0010100 1010101 Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, strin Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Why languages? What have we learned? 1. Languages are used to write applications 2. Developers write high level code in these languages 3. Every language has a compiler which converts the developer code into 01 Computer RAM C C++ Java Javascript Golang Rust Compiler 0100100 0010100 1010101 SSD The only language that the computer can process or execute is called machine language. It consists of only 0s and 1s in binary, that a computer can understand. In short, the computer only understands binary code, i.e 0s and 1s. Computers only store data (regardless of what kind) as bits. This bits will form everything in the computer, from the operating system, to the applications down to the files(all types videos, audio, photos) that the application runs. Hence any computer part only understands and stores 0s and 1s and nothing else hence we have to convert finally to them. Interpreted vs compiled languages Compiler Why languages? Interpreted vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, strin Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises What are compilers - Compilers convert high level developer friendly code into 0s and 1s Interpreted vs compiled languages Compiler Lets see it in action - The C++ compiler is called g++ Step 1 - write code Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, strin Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Interpreted vs compiled languages Compiler Lets see it in action - The C++ compiler is called g++ Step 1 - write code Step 2 - Compile code Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, strin Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Interpreted vs compiled languages Compiler Lets see it in action - The C++ compiler is called g++ Step 1 - write code Step 2 - Compile code Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, strin Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Step 3 - Run the code (put it in ram The command in step-2 is converting a C++ code (in file a.cpp) into a binary file named temp (contains 0s and 1s). Once you created the temp file now you can send this to anyone and finally everyone can run this temp file in their ram and can see hello world on their screen. For example if you GTA-5 game then this file is stored in your SSD as a temp file like above(binary) this is done so that you don't have to care about all the compilers thing and when you run this file then its execution is started in RAM which understands the binary file. Interpreted vs compiled languages Compiler But JS is di erent (interpreted) ff Step 1 - write code Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, strin Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Interpreted vs compiled languages Compiler But JS is di erent (interpreted) Step 1 - write code Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, strin Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Step 2 - Run code ff In Javascript, there is no need to completely convert the code file into binary first and then run it into the RAM. In Javascript, line by line conversion is done because of which first only the first line will be converted(to 0s and 1s) and then run it then the second line will be converted and then RAM will run that line Interpreted vs compiled languages Compiler Compiled languages 1. First need to compile, then need to run 2. Usually don’t compile if there is an error in the code 3. Example - C++, Java, Rust, Golang Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, strin Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Interpreted Languages 1. Usually go line by line 2. Can run partially if the error comes later 3. Example - Javascript, Python In compilation or in case of compiled languages there is a need to generate a separate output file (binary file) and then this complete file needs to be executed(run). In a interpreter or in case of interpreted languages every line is interpreted (converted into 0s and 1s) on by one and then the converted part is run then it goes to the second line does the same thing and so on and then these 0s and 1s are executed(run) inside the computer. Here we have not converted into a binary file like we did in compiler case. These interpreter and all the required things are present inside the browser js engines and also in nodejs environment(nodejs executes outside the browser environment) In compilation, the entire source code is converted into machine code at once and written into a binary file to be executed by the computer. In contrast, during interpretation, the interpreter goes through the source code and interprets it line by line, executing each line as it encounters it. Interpreted vs compiled languages Lets write some code If you want to run C++ code in your pc you will have to install a compiler as well and then but Please sign up on repl.it repl.it allows you to run C++ code without the need of a compiler Why repl.it? - It’s lets you compile (or interpret?) javascript code without having it locally on your machine lets try to run the hello world program Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, strin Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Interpreted vs compiled languages Lets write some code Now run this code Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, strin Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Interpreted vs compiled languages Lets write some code Same code for C++ Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, strin Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Interpreted vs compiled languages What did we learn? Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, strin Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises JS is an interpreted language C++ is a compiled language Interpreted languages go line by line while executing, can partially run until an error comes Why is JS better than other languages There is a way in which you can run C++, java run in a browser but we don't do that very often Why languages? Scripting vs compiled languages Why JS >> Other languages in som Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, strin Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Browsers can only understand HTML/CSS/JS (not technically true) Thanks to Node.js , Javascript can also be used for “Backend Development” Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, strin Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Static vs dynamic languages Having types helps hence typescript was introduced. fi fi This below C++ code will run on a single core but if you add some syntax here then the same code can run on multiple cores or you can say you are now using multi-thread functionality .But this cannot be done in javascript. C++ Javascript Bene ts - More strict code Bene ts - Can move fast Process : Intel(R) Core(TM) i5-10300H CPU @ 2.50GHz, 2496 Mhz, 4 Core(s), 8 Logical Processor(s) Most consumer laptops, including your laptop with the Intel® Core™ i5-10300H, have only one CPU package. This package contains all the CPU cores and other components described earlier. Here are the details: Typical Consumer Laptops Single CPU Package: Consumer laptops generally have a single CPU package, which includes multiple cores. In your case, the single CPU package contains 4 physical cores. Components of the CPU Cores: Each core can independently process instructions. In your Intel® Core™ i5-10300H, there are 4 physical cores. Cache: There are levels of cache (L1, L2, and sometimes L3) that store frequently accessed data to speed up processing. Control Unit: Directs operations within the CPU, telling the cores what to do. Arithmetic Logic Unit (ALU): Performs arithmetic and logical operations. Registers: Small, fast storage locations within the CPU for immediate data processing needs. Since CPU cores generate heat, they are usually covered by a heat spreader and connected to the laptop’s cooling system, which typically includes a combination of heat sinks, thermal paste, and fans to dissipate the heat generated during operation. So, in summary, the cores are microscopic structures located on the silicon die within the CPU package, which is mounted on the motherboard of your laptop Cores: 4 physical cores. Each core can handle a separate task (or thread), which improves multitasking and overall performance for multi-threaded applications. Logical Processors: 8 logical processors. This means that each physical core supports Intel's Hyper-Threading technology, allowing each core to handle two threads simultaneously. This effectively doubles the number of tasks the CPU can handle at once compared to a processor without Hyper-Threading. Sure, let's break down what "logical processors" and "Hyper-Threading technology" mean: ### Logical Processors - **Physical Cores**: These are the actual hardware units in a CPU that perform computations. In your case, there are 4 physical cores. - **Logical Processors**: These are the virtual cores that the operating system sees and can use. Each physical core can appear as two logical processors if Hyper-Threading is enabled. ### Hyper-Threading Technology - **Hyper-Threading**: This is a technology developed by Intel that allows a single physical core to act as two logical processors. This means each core can handle two threads (sets of instructions) simultaneously. ### How It Works 1. **Without Hyper-Threading**: A core can only work on one thread at a time. If a task is waiting for data to be fetched from memory (which takes time), the core might sit idle. 2. **With Hyper-Threading**: The core can switch to another thread when the first thread is waiting, effectively using more of the core’s capacity and improving efficiency. ### Benefits - **Improved Multitasking**: With more logical processors, your system can handle more tasks at once without significant slowdowns. - **Better Performance**: Applications that are designed to use multiple threads (such as video editing software, 3D rendering programs, and games) can run more efficiently. ### Example - If you are running multiple applications at the same time (e.g., a web browser, a game, and a video player), Hyper-Threading allows the CPU to manage these tasks more efficiently by distributing them across more logical processors. In essence, Hyper-Threading allows each core to do more work by keeping it busier, leading to better performance and responsiveness in multi-threaded applications and scenarios where multiple tasks are running concurrently. The terms "thread" and "process" are fundamental concepts in computer science, particularly in the context of operating systems and CPU operation. Here’s a breakdown of the differences between them: ### Process - **Definition**: A process is an independent program in execution. It has its own memory space, system resources, and can be thought of as a separate instance of a running application. - **Memory**: Each process has its own address space in memory. It cannot directly access the memory of other processes. - **Resources**: Processes have their own resources such as file handles, network connections, and other system resources. - **Isolation**: Processes are isolated from each other by the operating system to prevent one process from interfering with another. - **Context Switching**: Switching between processes involves more overhead because it requires saving and loading the process state, including the memory space and resources. ### Thread - **Definition**: A thread is the smallest unit of execution within a process. A single process can have multiple threads that share the same memory space and resources. - **Memory**: Threads within the same process share the same address space, allowing them to access the same variables and data structures. - **Resources**: Threads share the same resources allocated to their parent process. This includes open files, network connections, and other system resources. - **Inter-Thread Communication**: Because threads share the same memory space, they can communicate with each other more easily compared to processes. - **Context Switching**: Switching between threads within the same process involves less overhead than switching between processes because threads share the same memory space and resources. ### Practical Example 1. **Process Example**: When you open a web browser, the operating system creates a process for it. This process is isolated from other processes, meaning it has its own memory and resources. 2. **Thread Example**: Within the web browser process, there may be multiple threads running concurrently. For instance, one thread might handle user input, another thread might render the web page, and another might handle network requests. These threads share the same memory space and resources but can execute independently and simultaneously. ### CPU Core Utilization - **Processes**: Multiple processes can be executed on different CPU cores simultaneously. This is managed by the operating system’s scheduler. - **Threads**: Multiple threads within the same process can also run on different CPU cores simultaneously, which is especially useful in multi-core processors. This is known as parallelism. In a typical JavaScript environment, the code execution is predominantly handled by a single main thread, regardless of the number of CPU cores available. Here’s how the execution would be distributed across the cores: ### Single Main Thread Execution 1. **Synchronous Code**: All synchronous code (`console.log('Start');`, `console.log('End');`) runs on the main JavaScript thread. 2. **Asynchronous Operations**: - The `setTimeout` function call initiates a timer, which is handled by the browser's Web API or Node.js’s internal API. This operation is managed by the underlying system and can utilize other CPU cores, but the callback execution still happens on the main thread. - The `Promise.resolve().then` schedules the promise resolution callback, which is also executed on the main thread once the promise is resolved. ### CPU Core Utilization - **Core 1 (Main Thread)**: This core handles all the synchronous code and the execution of asynchronous callbacks. - **Other Cores**: These may be used by the system to manage the underlying asynchronous operations (like the timer or I/O operations), but this usage is abstracted away from the JavaScript execution model. The actual JavaScript code that you write (including the callback functions) runs on the main thread. ### Example Execution on Cores Consider the same example code: ```javascript console.log('Start'); // 1 setTimeout(() => { console.log('Timeout'); // 4 }, 1000); Promise.resolve().then(() => { console.log('Promise'); // 3 }); console.log('End'); // 2 ``` 1. **Core 1 (Main Thread)**: - Executes `console.log('Start');` and prints "Start". - Calls `setTimeout`, initiating the timer (handled by the browser’s Web API). - Schedules the promise resolution callback. - Executes `console.log('End');` and prints "End". 2. **Other Cores (System-Level Management)**: - **Core 2**: May handle the timer set by `setTimeout` using the system’s timer management functionality. - **Core 3**: May handle other background system tasks, such as I/O operations or event polling. - **Core 4**: Could be used for other processes or threads unrelated to the JavaScript execution. 3. **Returning to Core 1 (Main Thread)**: - Once the promise resolves, the `then` callback is placed in the message queue and executed by the main thread, printing "Promise". - After the 1000ms timer completes, the `setTimeout` callback is placed in the message queue and executed by the main thread, printing "Timeout". ### Summary - **JavaScript Code**: Runs on a single main thread (Core 1 in this example). - **Asynchronous Operations**: Managed by the system and may utilize multiple cores, but their completion callbacks are handled by the main thread. - **Multi-Core Utilization**: Other cores can be used for system-level management of asynchronous tasks, but explicit JavaScript code execution remains single-threaded unless using Web Workers or similar concurrency mechanisms. To achieve true parallel execution of JavaScript code across multiple cores, you would need to use Web Workers (in browsers) or worker threads (in Node.js). These allow for concurrent execution in separate threads, each potentially running on different CPU cores. When JavaScript code includes both asynchronous operations and synchronous code, the execution is managed by the event loop. Here’s a detailed explanation of how this works, including whether it happens on multiple cores: ### Execution Model 1. **Single-Threaded Execution**: JavaScript executes all synchronous code on a single thread. The main thread processes the call stack, which holds the function calls and executes them one by one. 2. **Event Loop**: The event loop plays a crucial role in managing asynchronous operations. It continuously checks the call stack and the message queue. When the call stack is empty, the event loop picks the first message from the queue and pushes it onto the call stack for execution. ### Asynchronous Operations 1. **Initiation**: When an asynchronous operation (like an HTTP request, a timeout, or a promise) is initiated, it is typically handed off to the browser's Web APIs or Node.js’s internal APIs. These operations run independently of the main JavaScript thread. 2. **Completion**: Once the asynchronous operation completes, a callback function or a promise resolution is placed in the message queue. ### Steps in Execution 1. **Synchronous Code Execution**: All synchronous code is executed first. If an asynchronous operation is encountered, it is initiated and then the synchronous code continues. 2. **Event Loop Handling**: After the synchronous code finishes, the event loop checks the message queue for any pending callbacks or promise resolutions from completed asynchronous operations. 3. **Callback Execution**: The callbacks or promise resolutions are pushed onto the call stack and executed one by one as the call stack becomes empty. ### Multi-Core Considerations - **Main Thread**: All JavaScript code, both synchronous and asynchronous callbacks, runs on the main single thread. This thread handles the execution sequence described above. - **Web APIs/Node.js Internals**: Asynchronous operations may utilize underlying system threads provided by Web APIs (in browsers) or Node.js internals. For example, network requests, file I/O, and timers are handled by these underlying systems, which can use multiple cores. - **Web Workers/Worker Threads**: If explicit parallelism is needed, Web Workers (in browsers) or worker threads (in Node.js) can be used. These allow JavaScript code to run in separate threads, enabling true multi-core utilization. However, these workers run in isolated contexts and do not share the main thread’s execution environment. ### Example Scenario Consider the following code: ```javascript console.log('Start'); // 1 setTimeout(() => { console.log('Timeout'); // 4 }, 1000); Promise.resolve().then(() => { console.log('Promise'); // 3 }); console.log('End'); // 2 ``` ### Execution Steps 1. **Synchronous Execution**: - `console.log('Start');` is executed and prints "Start". - `setTimeout` is called, initiating a timer in the browser’s Web API. - `Promise.resolve().then` schedules a promise resolution. - `console.log('End');` is executed and prints "End". 2. **Event Loop**: - The call stack is now empty. The event loop checks the message queue. - The promise resolution callback `() => console.log('Promise');` is in the message queue and gets executed, printing "Promise". - After the 1000ms timer completes, the `setTimeout` callback `() => console.log('Timeout');` is placed in the message queue and executed, printing "Timeout". ### Summary - **Main Thread**: Synchronous code and asynchronous callbacks all run on the main single thread. - **Underlying Systems**: Asynchronous operations (like timers, I/O) are managed by underlying systems (Web APIs or Node.js internals) which may use multiple cores. - **Explicit Multi-Core Utilization**: For true multi-core execution in JavaScript, you would need to use Web Workers or worker threads, which run in separate threads but require explicit handling and do not share the same execution context as the main thread. Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, strin Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Single threaded nature of JS On each core of your machine you can run processes. Hence better if we have many cores so that we can run many softwares/processes at once. Cores in a computer's CPU refer to the number of individual processing units capable of executing instructions independently. More cores generally lead to better multitasking capabilities and enhanced performance, particularly in applications optimized for multi-core systems. What if we have more than 10 processes to run on a computer with 10 cores? Ans : Context switching : Context switching is the process of switching the CPU from one process, task or thread to another. In a multitasking operating system, such as Linux, the CPU has to switch between multiple processes or threads in order to keep the system running smoothly. This is necessary because each CPU core without hyperthreading can only execute one process or thread at a time. If there are many processes or threads running simultaneously, and very few CPU cores available to handle them, the system is forced to make more context switches to balance the CPU resources among them. Mac Machine 1 2 3 4 5 6 7 8 On one core two processes cannot run parallely and simultaneously, to do this two different cores are assigned. If I want to run two different nodejs processes on my computer than a single core will not be able to execute together, it might context switch so run first one a little bit then second one then again first one and all. Python is also uses interpreter and is single-threaded language. SEE MORE ON PAGE 10 Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, strin Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Single threaded nature of JS Javascript main code(main thread) can run on one core and now since javascript is single threaded you cannot make this code run on more than one core like some part of the code on one core and another part of the code on other core what you can do is context switch or delgating the task. So in case of setTimeout functions or similar async functions Javascript delegates the task to Nodejs or browser or the appropriate thing.Context switching is done in case when you have all the 10 cores busy let us say and you want to run 12 process then the computer will context switch between the processes which are not running currently and run the process at that core which you want to run. Mac Machine JS can only use one of these at a time It is single threaded This is why it is considered to be a bad language for scalable systems There is a way to make it use all cores of your machine 1 2 3 4 5 6 7 8 Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, strin Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Single threaded nature of JS Using a single core of your machine. All this code is getting executed on a single core. More practically, JS runs line by line and only One line runs at a time Mac Machine 1 2 3 4 5 6 7 8 Simple primitives In JavaScript, "primitives" refer to the most basic data types that are not objects and have no methods. They are immutable, meaning their values cannot be changed once created. JavaScript has several primitive data types: Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, str booleans) Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Characteristics of Primitives Immutability: Primitives are immutable, meaning their values cannot be changed. For example, if you have a string let str = "hello";, you cannot change an individual character of the string. You would need to create a new string instead. Passed by Value: When you assign or pass a primitive value, JavaScript copies the value, so any changes to the new value do not affect the original. Primitive Wrapper Objects Variables (let, var, const) Although primitives are not objects, JavaScript automatically converts primitives to their corresponding object wrappers when necessary. For Data types - strings, numbers and booleans example, you can call methods on strings because JavaScript temporarily wraps the string primitive in a String object: If/else Loops - For loop let str = "hello"; console.log(str.toUpperCase()); // Outputs: "HELLO" In this example, str is a primitive, but the .toUpperCase() method works because JavaScript automatically creates a String object wrapper around the primitive to call the method. Let’s write some code 1. Write the program to greet a person given their rst and last name 2. Write a program that greets a person based on their gender. (If else) 3. Write a program that counts from 0 - 1000 and prints (for loop) fi Primitives: Basic data types in JavaScript that are not objects and are immutable. Types: Number, String, Boolean, Undefined, Null, Symbol, BigInt. Characteristics: Immutable and passed by value. Primitive Wrappers: JavaScript temporarily wraps primitives in their corresponding object wrappers to allow method calls. Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Complex Data Types Strict vs dynamic languages Definition: Complex data types (also known as reference types) are more elaborate structures that can hold Single threaded nature of JS multiple values and offer various methods. They include arrays and objects, and are mutable Simple primitives in JS (number, str booleans) primitives in JS (arrays, obje Mutability: Complex data types are mutable, meaning you can change their contents. For example, you can add, Complex Functions in Javascript modify, or delete properties in an object or elements in an array. Practise problem solving Callback functions, Event loop, callba Callback hell and Promises let arr = [1, 2, 3]; Complex primitives arr.push(4); // Modifies the array by adding a new element console.log(arr); // Outputs: [1, 2, 3, 4] 1. Arrays 2. Objects let obj = { a: 1 }; obj.b = 2; // Adds a new property to the object console.log(obj); // Outputs: { a: 1, b: 2 } Passed by Reference: When you assign a complex data type to a new variable or pass it to a function, you are passing a reference to the original value, not a copy. This means changes to the referenced value will affect the original value. Let’s write some code 1. Write a program prints all the even numbers in an array 2. Write a program to print the biggest number in an arrya 3. Write a program that prints all the male people’s rst name given a complex object 4. Write a program that reverses all the elements of an array fi Summary of Differences Immutability vs. Mutability: Primitives are immutable; complex data types are mutable. Value vs. Reference: Primitives are passed by value (a copy of the value); complex data types are passed by reference (a reference to the original object). Methods: Primitives do not have methods; complex data types have methods and can perform various operations. These differences affect how data is managed and manipulated in JavaScript, influencing performance, memory usage, and the behavior of code. Functions Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, str booleans) Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Functions let you 1. Abstract out logic in your program 2. Take arguments as an input 3. Return a value as an output 4. You can think of them as an independent program that is supposed to do something given an input 5. Functions CAN take other functions as input - this will confuse you (callbacks) fi Let’s write some code 1. Write a function that nds the sum of two numbers 2. Write another function that displays this result in a pretty format 3. Write another function that takes this sum and prints it in passive tense Functions Functions let you 1. Abstract out logic in your program 2. Take arguments as an input 3. Return a value as an output 4. You can think of them as an independent program that is supposed to do something given an input 5. Functions CAN take other functions as input - this will confuse you (callbacks) https://gist.github.com/hkirat/898ac1da32b6b347a8c0c3e73e1c0666 Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, str booleans) Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Why languages? Scripting vs compiled languages Why JS >> Other languages in some use-cases Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, strings, booleans) Complex primitives in JS (arrays, objects) Functions in Javascript Practise problem solving Callback functions, Event loop, callback queue Callback hell and Promises Callback functions, event loops, callback queue Synchronous vs Asynchronous functions Synchronous fi fi All the code we’ve written until now All code running line by line (hence sync) Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, str booleans) Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Asynchronous Asynchronous functions in programming are those that allow a program to start a potentially longrunning operation and continue executing other tasks without waiting for that operation to complete. This is particularly important in environments like web browsers or Node.js, where waiting for an operation to nish (like fetching data from a server or reading a large le) could make the application unresponsive. Callback functions, event loops, callback queue Synchronous vs Asynchronous functions Synchronous Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, str booleans) Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Callback functions, event loops, callback queue Synchronous vs Asynchronous functions Asynchronous (setTimeout) Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, str booleans) Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Callback functions, event loops, callback queue fl http://latent ip.com/loupe/ Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, str booleans) Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Callback functions, event loops, callback queue http://latent ip.com/loupe/ fl Better example Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, str booleans) Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Callback functions, event loops, callback queue http://latent ip.com/loupe/ More examples? fl Network calls File system calls Database calls setInterval Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, str booleans) Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Callback hell, Promises Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, str booleans) Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Disclaimer - This is going to be overwhelming, especially for beginners Please don’t worry if you don’t understand the next section, we don’t need it for a while Callback hell, Promises https://gist.github.com/hkirat/502ea4573a045804be95083ce5af94dc Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, str booleans) Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Callback hell, Promises https://gist.github.com/hkirat/f7780b5061182b7281d37c23951e916d Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, str booleans) Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises What’s left? fl Async await syntax in promises Next week/of ine video Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, str booleans) Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises Assignments Why languages? Scripting vs compiled languages Why JS >> Other languages in some u Strict vs dynamic languages Single threaded nature of JS Simple primitives in JS (number, str booleans) Complex primitives in JS (arrays, obje Functions in Javascript Practise problem solving Callback functions, Event loop, callba Callback hell and Promises For today 1. Create a counter in Javascript (counts down from 30 to 0) 2. Calculate the time it takes between a setTimeout call and the inner function actually running 3. Create a terminal clock (HH:MM:SS) There will be a video on how to install node.js and run tests locally for the main assignments for this week