JavaScript Flashcards

1
Q

for Each on array

A

arr.forEach(function(part, index, theArray) {
theArray[index] = “hello world”;
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

window.open

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the difference between window.location.href () and window.open () methods in JavaScript

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

date

A

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;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

comparing dates

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

template literal/string and tagged template literals

A

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}/']

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

JavaScript Event Delegation

A

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 &amp;&amp; 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 &amp;&amp; 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!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Element.matches API

A
// Get the parent DIV, add click listener...
document.getElementById("myDiv").addEventListener("click",function(e) {
	// e.target was the clicked element
  if (e.target &amp;&amp; e.target.matches("a.classA")) {
    console.log("Anchor element clicked!");
	}
});
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

ECMA Script vs ES6

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

ECMA Script vs Javascript

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

New features in JS engines before in ECMAScript standard

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What name to use? ECMA or ES6

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

check TC39 Finished Proposals for a list of features to be included in the next specification

A

https://github.com/tc39/proposals/blob/master/finished-proposals.md

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Browser Javascript feature support

A

https://kangax.github.io/compat-table/es6/

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is V8?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Understanding How the Chrome V8 Engine Translates JavaScript into Machine Code

A

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/

17
Q

node js ecma script/ javascript support

A

https://node.green/

18
Q

How to check if Node.js supports ES6 language feature

A

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/

19
Q

JavaScript / ECMAScript

A

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.

20
Q

Intro to Javascript

A

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
21
Q

Why Javascript - on the CLient

A

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

22
Q

Why Javascript - on the Server

A

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

23
Q

Why Javascript - For Native applications

A

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

24
Q

Why Javascript

A

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

25
Q

Javascript on Client

Javascript on the server

A

Javascript on Client - usually we are refering to a web browser; it could be native apps like React native

we run with a script tag in html or
alert(“hi”)

or have it in another file

this will load the javascript

it is usually built in web browser for some sort of interaction

javascript running in webbrowser has access to DOM, Document object Model

document object exists when running javascript in web browser
document.getElementById(“submit”)
javascript on client is used for created interfaces or interacting with elements in the browser with DOM

on the server side, it is not usually building an interface but like a webservice or service in general like reading and writing files, interacting with the database

we need node.js to run javascript on the server side
since we do not any browser or script tags on the server side. we have to install node.js on the server and execute any javascript file
> node index.js

DOM does not exist in node js but we get packages; some of them are built into node itself

const filesystem = require(“fs”);
fileSystem.writeFileSync(“helloWorld.txt”,”Hello World”);
console.log(“the file helloWorld.txt has been created”);
there is a repository of 3 rd party packages called NPM, which contains packages for anything

26
Q

Tools for writing javascript

A

Visual studio code

Source control management
build in terminal
Customizable and extensible
Free, cross- platform and open-source

27
Q

VS code extension

A

ESLint - find and fix problems in your javascript code before it hits the production
Prettier - Automatic doe formatter, so you donot have to care about that extra spaces and focus on coding
Javascript (ES6) code snippets: Avoid redundant typing with shortcuts to most used code fragments

28
Q

Node.js

A

it is the javascript runtime
execute javascript code outside of the browser
even if you build web application that runs inside the browser, node.js will provide you the environment to run all the tools that you need to build your javascript application whether it is inside or outside the browser

javascript ecosystem evolves so quickly, so is node.js

install nodejs using NVM - Node Version Manager
manage updates and multiple environments

for macOS,Linux or WSL users
github.com/nvm-sh/nvm

for Windows users
github.com/coreybutler/nvm-windows

nvm install node

29
Q

Read https://docs.microsoft.com/en-us/windows/nodejs/setup-on-windows

A

https://docs.microsoft.com/en-us/windows/nodejs/setup-on-windows

30
Q

using template literal instead of place holders/substitutions

A

anything that is not in quotes javascript thinks that it is a command
you could include emoji in your console.log
you could use single quotes or double quotes

template literals vs substitutions

const place ="world";
const greeting="Hello";
back tick - template literal - this allows to interpolate or combine text with programmatic values 
console.log(`${greeting},${place}`);

console.log(“%s,%s”,greeting,place); we could put as many

Javascript application is just a folder with files or other folders in it that contain your code

31
Q

running javascript code with node.js for console, template literal

A

for running in terminal:node index

index.js:
const Greeting="welcome";
const Name="Peter";
console.log(`${Greeting},${Name}`);

node puts the console message to the same window as the terminal that runs it

welcome,Peter

32
Q
let arr1 = [1, 2, 3,"sparse"];
let arr2 = ['hello', ...arr1, 'world'];
console.log(arr2);
let MeasureColumnsData=
[
  {
    "columnName": "ReportStartDate",
    "columnDescription": "start date for the loaded file data"
  },
  {
    "columnName": "ReportEndDate",
    "columnDescription": "end date for the loaded file data"
  } ,
  {
    "columnName": "Medical_Record_Number",
    "columnDescription": "patient MRN - this needs to be a numeric"
  }
]
console.log(MeasureColumnsData);

var measurecolAoA = MeasureColumnsData.map((el) => Object.values(el))

console. log(measurecolAoA);
console. log(measurecolAoA[0]);

 let workSheetColumnLength = measurecolAoA[0].map((a, i) => ({
        wch: Math.max(...measurecolAoA.map((a1) => a1[i].toString().length)),
      }));

console.log(workSheetColumnLength);

A
https://jsfiddle.net/
["hello", 1, 2, 3, "sparse", "world"]
[{
  columnDescription: "start date for the loaded file data",
  columnName: "ReportStartDate"
}, {
  columnDescription: "end date for the loaded file data",
  columnName: "ReportEndDate"
}, {
  columnDescription: "patient MRN - this needs to be a numeric",
  columnName: "Medical_Record_Number"
}]
[["ReportStartDate", "start date for the loaded file data"], ["ReportEndDate", "end date for the loaded file data"], ["Medical_Record_Number", "patient MRN - this needs to be a numeric"]]
["ReportStartDate", "start date for the loaded file data"]
[{
  wch: 21
}, {
  wch: 40
}]
>_
33
Q

Split and Pop

A

https://www.encodedna.com/2014/02/find-the-file-extension-using-javascript-jquery.htm

34
Q

include

A

https://stackoverflow.com/questions/42790602/how-do-i-check-whether-an-array-contains-a-string-in-typescript

35
Q

Recreate object map with json

A

https://stackoverflow.com/questions/40348171/es6-map-an-array-of-objects-to-return-an-array-of-objects-with-new-keys

36
Q

Var, Let, and Const – What’s the Difference?

A

https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/

So just in case you missed the differences, here they are:

var declarations are globally scoped or function scoped while let and const are block scoped.
var variables can be updated and re-declared within its scope; let variables can be updated but not re-declared; const variables can neither be updated nor re-declared.
They are all hoisted to the top of their scope. But while var variables are initialized with undefined, let and const variables are not initialized.
While var and let can be declared without being initialized, const must be initialized during declaration.

https://ui.dev/var-let-const/

37
Q

double == and triple ===

A

https://codeburst.io/javascript-double-equals-vs-triple-equals-61d4ce5a121a