JavaScript Flashcards
(37 cards)
for Each on array
arr.forEach(function(part, index, theArray) {
theArray[index] = “hello world”;
});
window.open
window.open(URL, name, specs, replace)
Parameter Description
URL Optional. Specifies the URL of the page to open. If no URL is specified, a new window/tab with about:blank is opened
name Optional. Specifies the target attribute or the name of the window. The following values are supported:
_blank - URL is loaded into a new window, or tab. This is default
_parent - URL is loaded into the parent frame
_self - URL replaces the current page
_top - URL replaces any framesets that may be loaded
name - The name of the window (Note: the name does not specify the title of the new window)
specs Optional. A comma-separated list of items, no whitespaces. The following values are supported:
channelmode=yes|no|1|0 Whether or not to display the window in theater mode. Default is no. IE only
directories=yes|no|1|0 Obsolete. Whether or not to add directory buttons. Default is yes. IE only
fullscreen=yes|no|1|0 Whether or not to display the browser in full-screen mode. Default is no. A window in full-screen mode must also be in theater mode. IE only
height=pixels The height of the window. Min. value is 100
left=pixels The left position of the window. Negative values not allowed
location=yes|no|1|0 Whether or not to display the address field. Opera only
menubar=yes|no|1|0 Whether or not to display the menu bar
resizable=yes|no|1|0 Whether or not the window is resizable. IE only
scrollbars=yes|no|1|0 Whether or not to display scroll bars. IE, Firefox & Opera only
status=yes|no|1|0 Whether or not to add a status bar
titlebar=yes|no|1|0 Whether or not to display the title bar. Ignored unless the calling application is an HTML Application or a trusted dialog box
toolbar=yes|no|1|0 Whether or not to display the browser toolbar. IE and Firefox only
top=pixels The top position of the window. Negative values not allowed
width=pixels The width of the window. Min. value is 100
replace Optional. Specifies whether the URL creates a new entry or replaces the current entry in the history list. The following values are supported:
true - URL replaces the current document in the history list
false - URL creates a new entry in the history list
Return Value: A reference to the newly created window, or null if the call failed
What is the difference between window.location.href () and window.open () methods in JavaScript
window. location.href is a property from (window.location), it returns current url location in browser and when change it it will redirect the same page to the new url.
window. location.href = ‘yourwebsiteurl’; window.open() is a method that will open the page you request inside it in new window.
window. open(‘yourwebsiteurl
date
startDate = new Date(1990, 0, 5);
january 51990 -0 jan
0=sunday 1=monday 6=saturday
const day = (d || new Date()).getDay(); // Prevent Saturday and Sunday from being selected. return day !== 0 && day !== 6;
comparing dates
The Date object will do what you want - construct one for each date, then compare them using the >, =.
The ==, !=, ===, and !== operators require you to use date.getTime() as in
var d1 = new Date(); var d2 = new Date(d1); var same = d1.getTime() === d2.getTime(); var notSame = d1.getTime() !== d2.getTime(); to be clear just checking for equality directly with the date objects won't work
var d1 = new Date(); var d2 = new Date(d1);
console. log(d1 == d2); // prints false (wrong!)
console. log(d1 === d2); // prints false (wrong!)
console. log(d1 != d2); // prints true (wrong!)
console. log(d1 !== d2); // prints true (wrong!)
console. log(d1.getTime() === d2.getTime()); // prints true (correct)
template literal/string and tagged template literals
https://stackoverflow.com/questions/27565056/es6-template-literals-vs-concatenated-strings
If you are using template literals only with placeholders (e.g. Hello ${person.name}
) like in the question’s example, then the result is the same as just concatenating strings. Subjectively it looks better and is easier to read, especially for multi-line strings or strings containing both ‘ and “ since you don’t have to escape those characters any more.
Readability is a great feature, but the most interesting thing about templates are Tagged template literals:
let person = {name: 'John Smith'}; let tag = (strArr, name) => strArr[0] + name.toUpperCase() + strArr[1]; Console.log(tag `My name is ${person.name}!`); // Output: My name is JOHN SMITH! In the third line of this example, a function named tag is called. The content of the template string is split into multiple variables, that you can access in the arguments of the tag function: literal sections (in this example the value of strArr[0] is My name is and the value of strArr[1] is !) and substitutions (John Smith). The template literal will be evaluated to whatever the tag function returns.
The ECMAScript wiki lists some possible use cases, like automatically escaping or encoding input, or localization. You could create a tag function named msg that looks up the literal parts like My name is and substitutes them with translations into the current locale’s language, for example into German:
console.log(msgMy name is ${person.name}.
) // Output: Mein Name ist John Smith.
The value returned by the tag function doesn’t even have to be a string. You could create a tag function named $ which evaluates the string and uses it as a query selector to return a collection of DOM nodes, like in this example:
$a.${className}[href=~'//${domain}/']
JavaScript Event Delegation
https://davidwalsh.name/event-delegate
One of the hot methodologies in the JavaScript world is event delegation, and for good reason. Event delegation allows you to avoid adding event listeners to specific nodes; instead, the event listener is added to one parent. That event listener analyzes bubbled events to find a match on child elements. The base concept is fairly simple but many people don’t understand just how event delegation works. Let me explain the how event delegation works and provide pure JavaScript example of basic event delegation.
Let’s say that we have a parent UL element with several child elements:
<ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> <li>Item 5</li> <li>Item 6</li> </ul> Let's also say that something needs to happen when each child element is clicked. You could add a separate event listener to each individual LI element, but what if LI elements are frequently added and removed from the list? Adding and removing event listeners would be a nightmare, especially if addition and removal code is in different places within your app. The better solution is to add an event listener to the parent UL element. But if you add the event listener to the parent, how will you know which element was clicked?
Simple: when the event bubbles up to the UL element, you check the event object’s target property to gain a reference to the actual clicked node. Here’s a very basic JavaScript snippet which illustrates event delegation:
// Get the element, add a click listener... document.getElementById("parent-list").addEventListener("click", function(e) { // e.target is the clicked element! // If it was a list item if(e.target && e.target.nodeName == "LI") { // List item found! Output the ID! console.log("List item ", e.target.id.replace("post-", ""), " was clicked!"); } }); Start by adding a click event listener to the parent element. When the event listener is triggered, check the event element to ensure it's the type of element to react to. If it is an LI element, boom: we have what we need! If it's not an element that we want, the event can be ignored. This example is pretty simple -- UL and LI is a straight-forward comparison. Let's try something more difficult. Let's have a parent DIV with many children but all we care about is an A tag with the classA CSS class:
// Get the parent DIV, add click listener... document.getElementById("myDiv").addEventListener("click",function(e) { // e.target was the clicked element if (e.target && e.target.matches("a.classA")) { console.log("Anchor element clicked!"); } }); Using the Element.matches API, we can see if the element matches our desired target.
Since most developers use a JavaScript library for their DOM element and event handling, I recommend using the library’s method of event delegation, as they are capable of advanced delegation and element identification.
Hopefully this helps you visually the concept behind event delegation and convinces you of delegation’s power!
Element.matches API
// Get the parent DIV, add click listener... document.getElementById("myDiv").addEventListener("click",function(e) { // e.target was the clicked element if (e.target && e.target.matches("a.classA")) { console.log("Anchor element clicked!"); } });
ECMA Script vs ES6
Officially, the name is “ECMAScript 2015 Language” and it’s the 6th Edition of the ECMA-262 standard.
ES6 is the last big release, and future versions will be smaller, and they will be released more frequently.
ECMA Script vs Javascript
Is it ECMAScript or JavaScript? In everyday life, you can use the terms ECMAScript and JavaScript interchangeably. ECMAScript is a specification of a language. JavaScript is an implementation of that language among JScript and ActionScript. The language specification deals with abstract concepts such as “[[GetPrototypeOf]] internal slot” while JavaScript has a concrete getPrototypeOf method.
New features in JS engines before in ECMAScript standard
A new language feature goes through many phases before being included in the specification. It grows from an idea into a commented proposal and into an accepted language feature. Periodically, the committee responsible for the ECMAScript specification collects accepted language features and writes an updated edition of the ECMAScript specification.
In the last stage, before the feature being accepted into the language, the committee requires that two shipping VMs exist that implement the feature. This means that Chrome and Firefox can implement a language feature before it’s included in an official ECMAScript specification.
The ‘implementation first’-approach means that you will be checking if a JS engine supports a specific language feature instead of supporting a specific ECMAScript version. The situation is similar to CSS, HTML, and browser runtime environment. Instead of checking for a version number, you’d check if Intersection Observer API works in your choice of browsers.
What name to use? ECMA or ES6
JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997.
ECMAScript is the official name of the language.
From 2015 ECMAScript is named by year (ECMAScript 2015).
The ECMAScript 2015 Language version was the last big release. Future updates to the specification will be smaller. New language features will be implemented in JavaScript engines before they are officially included in the specification.
You should talk about
use ES6 to refer to “ECMAScript 2015 Language” (arrow functions, template strings, Promises), it’s shorter than ES2015, and both are unofficial, ES6 was the last big release, and the name is in line with the previous big release ES5, things change after that
after ES6, use names of language features, such as “globalThis” and “Array.prototype.flatMap”, the specification is only updated after working implementations exist in JS engines, check TC39 Finished Proposals for a list of features to be included in the next specification
for historically referring one year’s updates to the ECMAScript specification use ES[year]
https://www.w3schools.com/js/js_versions.asp#
:~:text=The%20latest%20JavaScript%20version%20
was,after%20the%20organization%20adopted%20JavaScript.
check TC39 Finished Proposals for a list of features to be included in the next specification
https://github.com/tc39/proposals/blob/master/finished-proposals.md
Browser Javascript feature support
https://kangax.github.io/compat-table/es6/
What is V8?
V8 is Google’s open source high-performance JavaScript and WebAssembly engine, written in C++. It is used in Chrome and in Node.js, among others. It implements ECMAScript and WebAssembly, and runs on Windows 7 or later, macOS 10.12+, and Linux systems that use x64, IA-32, ARM, or MIPS processors. V8 can run standalone, or can be embedded into any C++ application.
Understanding How the Chrome V8 Engine Translates JavaScript into Machine Code
High-level languages are abstracted from machine language. In the level of abstraction below, you can see how far JavaScript is abstracted from the machine level. C/C++ are relatively much closer to the hardware and hence much faster than other high-level languages.
V8 engine: V8 is a powerful open source Javascript engine provided by Google. So what actually is a Javascript Engine? It is a program that converts Javascript code into lower level or machine code that microprocessors can understand.
The Chrome V8 engine :
The V8 engine is written in C++ and used in Chrome and Nodejs.
It implements ECMAScript as specified in ECMA-262.
The V8 engine can run standalone we can embed it with our own C++ program.
https://www.freecodecamp.org/news/understanding-the-core-of-nodejs-the-powerful-chrome-v8-engine-79e7eb8af964/
node js ecma script/ javascript support
https://node.green/
How to check if Node.js supports ES6 language feature
New language features trickle down to Node.js in phases. Node uses Google’s V8 JavaScript engine for language implementation. New language features in Node depend on them being implemented first in V8. The V8 project pushes forward steadily and the team releases a new version roughly every six weeks. Then it’s up to the Node team to take up the new changes and incorporate them in Node.js.
https://bytearcher.com/articles/how-to-check-if-node-implements-es6-language-feature/
JavaScript / ECMAScript
JavaScript was developed for Netscape. Netscape 2 was the first browser to run JavaScript.
After Netscape the Mozilla foundation continued to develop JavaScript for the Firefox browser.
The latest JavaScript version was 1.8.5. (Identical to ECMAScript 5).
ECMAScript was developed by ECMA International after the organization adopted JavaScript.
The first edition of ECMAScript was released in 1997.
Intro to Javascript
JavaScript is a programming language
Originally designed to programmatically interact with elements of a web page
Add a click event to a button that shows an alert Change the style of an element
It is not Java
It is a c-like language
Was designed with Java in mind
It is dynamically typed and compiled JIT var x = 0; Code is compiled when it is run you do not need to compile it separately to run it,just run it. it works
Why Javascript - on the CLient
Javascript is everywhere
it is in the browser
browser has gone long way into fully fledged application development runtimes, they used to be just for running documents on the web, now they are for applications as well
you could build rich applications in the browsers that look like desktop applications
Client: The web has significantly evolved in the past 10 years in to a fully capable runtime environment for applications
Why Javascript - on the Server
Server : javascript on the server with Node.js runtime that executes javascript on the server
anything that you could do with C# or Java on the server, you could do it with javascript as well like reading writing files. interacting with the database
Why Javascript - For Native applications
Native: build native desktop and mobile applications with Electron, React Native and Native Script
these are the applications that you would install from app store on your phone or on the desktop
this is enabled by open source frameworks maintained by companies such as facebook and microsoft
Why Javascript
Javascript is the most used programming language in the world
all those social media website you love are written in javascript
Some of your favorite desktop applications such as VS Code and Slack are written in javascript
Javascript is a programming language that can be used just about anywhere to build just about anything