fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@ -0,0 +1,124 @@
---
title: JavaScript Tutorials and Other Resources
---
* <a href='http://jsforcats.com/' target='_blank' rel='nofollow'>JavaScript for Cats</a>
* <a href='https://javascript.info/' target='_blank' rel='nofollow'>The Modern JavaScript Tutorial</a>
* <a href='https://github.com/DrBoolean/mostly-adequate-guide' target='_blank' rel='nofollow'>Professor Frisby's Mostly Adequate Guide to Functional Programming</a>
* <a href='http://www.eloquentjavascript.net' target='_blank' rel='nofollow'>Eloquent Javascript</a> (<a href='https://watchandcode.com/courses/eloquent-javascript-the-annotated-version' target='_blank' rel='nofollow'>_annotated_</a>)
* <a href='http://speakingjs.com/es5/' target='_blank' rel='nofollow'>Speaking Javascript</a>
* <a href='http://exploringjs.com/es6/' target='_blank' rel='nofollow'>Exploring ES6</a>
* <a href='https://www.youtube.com/watch?v=Bv_5Zv5c-Ts' target='_blank' rel='nofollow'>Udemy - Javascript Understanding the Weird Parts (_first 3.5 hrs_)</a>
* <a href="https://www.youtube.com/playlist?list=PL0zVEGEvSaeEd9hlmCXrk5yUyqUag-n84">Functional programming in JavaScript</a>
* <a href='https://www.educative.io/collection/5679346740101120/5720605454237696?authorName=Arnav%20Aggarwal' target='_blank' rel='nofollow'>Introduction to JavaScript: First Steps</a>
* <a href='https://www.youtube.com/watch?v=v2ifWcnQs6M&index=1&list=PL62E185BB8577B63D' target='_blank' rel='nofollow'>Douglas Crockford's Videos</a>
* <a href='https://mbeaudru.github.io/modern-js-cheatsheet/' target='_blank' rel='nofollow'>Modern JS Cheatsheet</a>
* <a href='http://www.codeconquest.com/blog/top-50-websites-to-learn-javascript/' target='_blank' rel='nofollow'>The 50 Best Websites to Learn JavaScript</a>
* <a href='https://www.codementor.io/community/topic/javascript' target='_blank' rel='nofollow'>Codementor JavaScript tutorial</a>
* <a href='http://youmightnotneedjquery.com/' target='_blank' rel='nofollow'>You Might Not Need jQuery</a>
## References
* <a href='http://devdocs.io' target='_blank' rel='nofollow'>DevDocs</a>
* <a href='http://overapi.com/javascript' target='_blank' rel='nofollow'>OverAPI JavaScript Cheat Sheet</a>
* <a href='http://www.ecma-international.org/publications/standards/Ecma-262.htm' target='_blank' rel='nofollow'>ECMA-262</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript' target='_blank' rel='nofollow'>Mozilla Developer Network (MDN)</a>
Find javascript libraries at <a href='http://jster.net' target='_blank' rel='nofollow'>http://jster.net</a>
## Quick JavaScript
* <a href='https://repl.it/languages/Javascript' target='_blank' rel='nofollow'>REPL</a> (<a href='https://repl.it/languages/iojs/' target='_blank' rel='nofollow'>_node_</a>)
* <a href='http://jsbin.com' target='_blank' rel='nofollow'>JSBin</a>
* <a href='https://jsfiddle.net' target='_blank' rel='nofollow'>JSFiddle</a>
* <a href='http://codepen.io' target='_blank' rel='nofollow'>CodePen</a>
* <a href='http://coderpad.io' target='_blank' rel='nofollow'>CoderPad (_pair programming_)</a>
* <a href='http://c9.io' target='_blank' rel='nofollow'>C9 (_IDE_, _pair programming_)</a>
* <a href='http://www.objectplayground.com/' target='_blank' rel='nofollow'>Object Playground (_visualize objects_)</a>
* <a href='http://plnkr.co' target='_blank' rel='nofollow'>Plunker</a>
## Challenges
* <a href='http://codewars.com' target='_blank' rel='nofollow'>Code Wars</a>
* <a href='https://hackerrank.com' target='_blank' rel='nofollow'>Hacker Rank</a>
* <a href='http://codingame.com' target='_blank' rel='nofollow'>Coding Game</a>
* <a href='https://codefights.com/home' target='_blank' rel='nofollow'>CodeFights</a>
* <a href='http://es6katas.org' target='_blank' rel='nofollow'>ES6 Katas</a>
* <a href='https://projecteuler.net/archives' target='_blank' rel='nofollow'>Project Euler</a>
## Tutorials
* <a href='https://www.codecademy.com' target='_blank' rel='nofollow'>Codecademy</a>
* <a href='https://www.rithmschool.com' target='_blank' rel='nofollow'>RithmSchool</a>
## Exercises
* <a href='https://codility.com/programmers/lessons/' target='_blank' rel='nofollow'>Codility</a>
* <a href='http://coderbyte.com' target='_blank' rel='nofollow'>Coderbyte</a>
* <a href='http://exercism.io' target='_blank' rel='nofollow'>Exercism</a>
* <a href='https://javascript30.com/' target='_blank' rel='nofollow'>JavaScript30</a>
* <a href='https://www.javascript.com/' target='_blank' rel='nofollow'>Javascript.com (Pluralsight)</a>
## Editors
* <a href='https://code.visualstudio.com/' target='_blank' rel='nofollow'>Visual Studio Code</a>
Visual Studio Code includes built-in support for IntelliSense code completion, rich semantic code understanding and navigation, and code refactoring. It comes with a built-in debugger and git support and has a plethora of extensions.
* <a href='https://www.jetbrains.com/webstorm/' target='_blank' rel='nofollow'>Webstorm</a>
A full-feature IDE for Javascript, including code completion and support for live linting, version control, and testing. Made by Jet Brains and modelled after their IntelliJ Java IDE.
* <a href='http://brackets.io' target='_blank' rel='nofollow'>Brackets</a>
* <a href='http://atom.io' target='_blank' rel='nofollow'>Atom</a>
Open source text editor made by GitHub.
* <a href='https://www.sublimetext.com/' target='_blank' rel='nofollow'>Sublime Text</a>
## Blogs
* <a href='http://perfectionkills.com' target='_blank' rel='nofollow'>Perfection Kills</a>
* <a href='http://www.2ality.com/' target='_blank' rel='nofollow'>2ality</a>
* <a href='https://medium.com/the-javascript-collection' target='_blank' rel='nofollow'>JS collection on Medium</a>
* <a href='https://davidwalsh.name/' target='_blank' rel='nofollow'>David Walsh</a>
* <a href='http://superherojs.com/' target='_blank' rel='nofollow'>superheroJS</a>
## Podcasts
* <a href='https://devchat.tv/js-jabber' target='_blank' rel='nofollow'>JS Jabber</a>
## Video Tutorials
* <a href='https://www.youtube.com/watch?v=fju9ii8YsGs' target='_blank' rel='nofollow'>Derek Banas' Learn JS In One Video </a>
* <a href='https://www.youtube.com/watch?v=O8wwnhdkPE4'>Derek Banas' Object Oriented JavaScript</a>
* <a href='https://www.youtube.com/watch?v=YMvzfQSI6pQ'>JavaScript Fundamentals for Absolute Beginners 2018</a>
## Books
* <a href='https://www.manning.com/books/secrets-of-the-javascript-ninja' target='_blank' rel='nofollow'>Secrets of the JavaScript Ninja</a>
* <a href='http://pjabook.com/' target='_blank' rel='nofollow'>Programming JavaScript Applications</a>
* <a href='http://shop.oreilly.com/product/0636920025245.do' target='_blank' rel='nofollow'>Maintainable JavaScript</a>
* <a href='http://addyosmani.com/resources/essentialjsdesignpatterns/book/' target='_blank' rel='nofollow'>Learning JavaScript Design Patterns</a>
* <a href='https://github.com/airbnb/javascript' target='_blank' rel='nofollow'>Airbnb JavaScript Style Guide</a>
* <a href='http://usejsdoc.org/' target='_blank' rel='nofollow'>JSDoc</a>
* <a href='https://leanpub.com/javascriptallongesix/read' target='_blank' rel='nofollow'>Javascript Allonge Six</a>
* <a href='https://github.com/getify/You-Dont-Know-JS' target='_blank' rel='nofollow'>You Don't Know JS</a>
6 books on JavaScript by Kyle Simpson. From beginner to advanced.
* <a href='http://www.eloquentjavascript.net' target='_blank' rel='nofollow'>Eloquent Javascript</a>
Fantastic, thorough introduction to the basics and features of Javascript, complete with in-browser interactive code
* <a href='https://github.com/DrBoolean/mostly-adequate-guide' target='_blank' rel='nofollow'>Professor Frisby's Mostly Adequate Guide to Functional Programming</a>
Quite in-depth guide to Functional Programming in Javascript
* <a href='https://github.com/bpesquet/thejsway' target='_blank' rel='nofollow'>The JavaScript Way</a>
* <a href='https://github.com/getify/Functional-Light-JS' target='blank' rel='nofollow'>Functional Light JS</a>
This book aims to be a useful companion for anyone wishing to (re)discover the many facets of JavaScript. From the very basics of programming up to front-end and back-end web development, a lot of topics are covered in a simple and accessible way. No prior knowledge needed!

View File

@ -0,0 +1,23 @@
---
title: Advantages and Disadvantages of JavaScript
---
# Advantages and Disadvantages of JavaScript
Like all computer languages, JavaScript has certain advantages and disadvantages. Many of the pros and cons are related to JavaScript executing often in a client's browser, but there are other ways to use JavaScript now that allow it to have the same benefits of server-side languages.
## Advantages of JavaScript
* **Speed**. Client-side JavaScript is very fast because it can be run immediately within the client-side browser. Unless outside resources are required, JavaScript is unhindered by network calls to a backend server. It also has no need to be compiled on the client side which gives it certain speed advantages (granted, adding some risk dependent on that quality of the code developed).
* **Simplicity**. JavaScript is relatively simple to learn and implement.
* **Popularity**. JavaScript is used everywhere in the web. The resources to learn JavaScript are numerous. StackOverflow and GitHub have many projects that are using Javascript and the language as a whole has gained a lot of traction in the industry in recent years especially.
* **Interoperability**. JavaScript plays nicely with other languages and can be used in a huge variety of applications. Unlike PHP or <a href='https://en.wikipedia.org/wiki/Server_Side_Includes' target='_blank' rel='nofollow'>SSI</a> scripts, JavaScript can be inserted into any web page regardless of the file extension. JavaScript can also be used inside scripts written in other languages such as Perl and PHP.
* **Server Load**. Being client-side reduces the demand on the website server.
* **Rich interfaces**. Drag and drop components or slider may give a rich interface to your website.
* **Extended Functionality**. Third party add-ons like Greasemonkey enable JavaScript developers to write snippets of JavaScript which can execute on desired web pages to extend its functionality.
* **Frameworks**. If there is anything JavaScript could thank for its wild success, its frameworks. With the rise in demand of the popular <a href='https://en.wikipedia.org/wiki/MEAN_(software_bundle)' target='_blank' rel='nofollow'>MEAN Stack</a>, JavaScript is giving developers a true bang for their buck. In addition to Node and React, both extremely helpful in web development and continually trending, other frameworks such as <a href='https://facebook.github.io/react-native/' target='_blank' rel='nofollow'>React Native</a>, are giving JavaScript developers the ability to create their own hybrid mobile applications. With just one language, developers can, and will, go far with JavaScript.
* **Versatility**. Nowadays, there are many ways to use JavaScript through <a href='https://nodejs.org/en/' target='_blank' rel='nofollow'>Node.js</a> servers. If you were to bootstrap node.js with Express, use a document database like <a href='https://www.mongodb.com/' target='_blank' rel='nofollow'>MongoDB</a>, and use JavaScript on the front-end for clients, it is possible to develop an entire JavaScript app from front to back using only JavaScript.
* **Updates**. Since the advent of EcmaScript 5 (the scripting specification that Javascript relies on), Ecma International has dedicated to updating JavaScript annually. So far, we have received browser support for ES6 in 2017 and look forward to ES7 being supported in future months.
## Disadvantages of JavaScript
* **Client-Side Security**. Because the code executes on the users' computer, in some cases it can be exploited for malicious purposes. This is one reason some people choose to disable Javascript.
* **Browser Support**. JavaScript is sometimes interpreted differently by different browsers. Whereas server-side scripts will always produce the same output, client-side scripts can be a little unpredictable. Don't be overly concerned by this though - as long as you test your script in all the major browsers you should be safe. Also, there are services out there that will allow you to test your code automatically on check in of an update to make sure all browsers support your code.

View File

@ -0,0 +1,80 @@
---
title: Angularjs Interview Questions
---
# Angularjs Interview Questions
Here's a list of the concepts that are frequently asked about in Angularjs interviews.
* What is AngularJS?
* What is the Model View Controller (MVC)?
* Two way data binding
* What is dependency injection and how does it work?
* What is $scope in AngularJS?
* What is $rootScope in AngularJS?
* How to implement routing in Angular?
* Explain directives
* How can we create a custom directive in Angular?
* Explain difference bewteen service and factory
* Explain $q service, deferred and promises
# Example Questions and Answers
Question: List out the Directives in AngularJS?
Answer: ngBind, ngModel, ngClass, ngApp, ngInit, ngRepeat
Question : What is $scope in AngularJS?
Answer: $scope in AngularJS is an object which refers to an application model. It is an object that binds view (DOM element) with the controller. In controller, model data is accessed via $scope object. As we know, AngularJS supports MV* pattern, $scope object becomes the model of MV*.
Question: What is SPA (Single page application) in AngularJS?
Answer: Single-Page Applications (SPAs) are web applications that load a single HTML page and dynamically update that page as the user interacts with the app. SPAs use AJAX and HTML to create fluid and responsive web apps, without constant page reloads. However, this means much of the work happens on the client side, in JavaScript.
A single HTML page here means UI response page from the server. The source can be ASP, ASP.NET, ASP.NET MVC, JSP and so on.
A single-page web application, however, is delivered as one page to the browser and typically does not require the page to be reloaded as the user navigates to various parts of the application. This results in faster navigation, more efficient network transfers, and better overall performance for the end user.
Question: What is routing in AngularJS?
Answer: Routing is a core feature in AngularJS. This feature is useful in building SPA (Single Page Application) with multiple views. In SPA application, all views are different Html files and we use Routing to load different parts of the application and it's helpful to divide the application logically and make it manageable. In other words, Routing helps us to divide our application in logical views and bind them with different controllers.
Question: Explain ng-repeat directive.
Answer: The ng-repeat directive is the most used and very useful AngularJS Directive feature. It iterates over a collection of items and creates DOM elements. It constantly monitors the source of data to re-render a template in response to change.
Question: What is the difference between ng-If and ng-show/ng-hide.
Answer: The ng-If directive only render DOM element if condition is true. where ng-show/ng-hide directive render the DOM element but it changes class of ng-hide/ng-show to maintain visibility of the element on the page.
Question: How do you cancel a timeout with AngularJs?
Answer: $timeout is AngularJs' wrapper for window.setTimeout, you cancel a timeout applying the function:
$timeout.cancel(function (){
// write your code.
});
Question: What is the Dependency Injection?
Answer: Dependency Injection (DI) is a software design pattern that deals with how components get hold of their dependencies.
The AngularJS injector subsystem is in charge of creating components, resolving their dependencies, and providing them to other components as requested.
Question : Explain ng-App directive.
Answer : The ng-app directive starts an AngularJS Application. It defines the root element. It automatically initializes or bootstraps the application when web page containing AngularJS Application is loaded. It is also used to load various AngularJS modules in AngularJS Application.
Question : Explain ng-init directive
Answer : The ng-init directive initializes an AngularJS Application data. It is used to put values to the variables to be used in the application. Eg:In the below example, we have initialized an array of countries,using JSON syntax to define array of countries.
```html
<div ng-app = "" ng-init = "countries = [{locale:'en-US',name:'United States'}, {locale:'en-GB',name:'United Kingdom'}, {locale:'en-FR',name:'France'}]">
...
</div>
```
Question: How do you share data between controllers?
Answer: Create an AngularJS service that will hold the data and inject it inside of the controllers.
Using a service is the cleanest, fastest and easiest way to test. However, there are couple of other ways to implement data sharing between controllers, like:
Using events
Using $parent, nextSibling, controllerAs, etc. to directly access the controllers
Using the $rootScope to add the data on (not a good practice)
Question: What is the difference between ng-if and ng-show/hide directives?
Answer: ng-if will only create and display the DOM element when its condition is true, if the condition is false or changes to false it will not create or destroy the created one.
ng-show/hide will always generate the DOM element but it will apply the css display property based on the evaluation of the condition.
#### More Information:
Here you can find other questions and answers:
* [AngularJS Interview Questions](https://www.tutorialspoint.com/angularjs/angularjs_interview_questions.htm)
* [10 AngularJS interview questions and answers](https://www.upwork.com/i/interview-questions/angularjs/)
* [50 Most Important AngularJS Interview Questions For 100% Success](http://www.techbeamers.com/latest-angularjs-interview-questions-answers/)

View File

@ -0,0 +1,101 @@
---
title: Arguments
---
The arguments object is an **array-like object** _(in that the structure of the object is similar to that of an array however it should not be considered an array as it has all the functionality of an object)_ that stores all of the arguments that you passed to a function and is proprietary to that function in particular. If you were to pass 3 arguments to a function, say `storeNames()`, those 3 arguments would be stored inside an object called **arguments** and it would look like this when we pass the arguments `storeNames("Mulder", "Scully", "Alex Krycek")` to our function:
* First, we declare a function and make it return the arguments object.
```javascript
function storeNames() { return arguments; }
```
* Then, when we execute that function with **n arguments**, 3 in this case, it will return the object to us and it will **look like** an array. We can convert it to an array, but more on that later...
```javascript
// If we execute the following line in the console:
storeNames("Mulder", "Scully", "Alex Kryceck");
// The output will be { '0': 'Mulder', '1': 'Scully', '2': 'Alex Kryceck' }
```
If you want to know more about this, such as converting it to an array or the optimization problem that comes with using the _slice(_) method and how to solve it, click on **read more** (Gitter Chat Only).
## Treat it as an array
You can invoke arguments by using `arguments[n]` (where _n_ is the index of the argument in the array-like object) but if you want to use it as an array for iteration purposes or applying array methods to it, you need to _convert it to an array_ by declaring a variable and using the Array.prototype.slice.call method (because _arguments_ is not an array):
```javascript
var args = Array.prototype.slice.call(arguments);
// or the es6 way:
var args = Array.from(arguments)
```
Since **slice()** has two (the parameter **end** is optional) parameters, you can grab a certain portion of the arguments by specifying (using the _slice.call()_ method renders these two parameters optional, not just _end_) the beginning and the ending of your portion; check out the following code:
```javascript
function getGrades() {
var args = Array.prototype.slice.call(arguments, 1, 3);
return args;
}
// Let's output this!
console.log(getGrades(90, 100, 75, 40, 89, 95));
// OUTPUT SHOULD BE: //
// [100, 75] <- Why? Because it started from index 1 and stopped at index 3
// so, index 3 (40) wasn't taken into consideration.
//
// If we remove the '3' parameter, leaving just (arguments, 1) we'd get
// every argument from index 1: [100, 75, 40, 89, 95].
```
### Optimization issues with Array.slice()
There is a little problem, it's not recommended to use slice in the arguments object (optimization reasons)...
> **Important**: You should not slice on arguments because it prevents optimizations in JavaScript engines (V8 for example). Instead, try constructing a new array by iterating through the arguments object.
>
> _by_ **_Mozilla Developer Network_** <a href='https://developer.mozilla.org/ca/docs/Web/JavaScript/Reference/Functions/arguments' target='_blank' rel='nofollow'>(reference)<a>
So, what other method is available to convert _arguments_ to an array? I recommend the for-loop (not the for-in loop), you can do it like this:
```javascript
var args = []; // Empty array, at first.
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i])
} // Now 'args' is an array that holds your arguments.
```
For more information on the optimization issues:
Optimization Killers: <a href='https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments' target='_blank' rel='nofollow'>Managing Arguments</a>
### ES6 rest parameter as a way to circumvent the arguments object
In ES2015/ES6 it is possible to use the rest parameter (`...`) instead of the arguments object in most places. Say we have the following function (non-ES6):
function getIntoAnArgument() {
var args = arguments.slice();
args.forEach(function(arg) {
console.log(arg);
});
}
That function can be replaced in ES6 by:
function getIntoAnArgument(...args) {
args.forEach(arg => console.log(arg));
}
note that we also used an arrow function to shorten the forEach callback!
The arguments object is not available inside the body of an arrow function.
The rest parameter must always come as the last argument in your function definition.
```function getIntoAnArgument(arg1, arg2, arg3, ...restOfArgs /*no more arguments allowed here*/) {
//function body
}```

View File

@ -0,0 +1,119 @@
---
title: Arithmetic Operation
---
JavaScript provides the user with five arithmetic operators: `+`, `-`, `*`, `/` and `%`. The operators are for addition, subtraction, multiplication, division and remainder respectively.
## Addition
**Syntax**
`a + b`
**Usage**
2 + 3 // returns 5
true + 2 // interprets true as 1 and returns 3
false + 5 // interprets false as 0 and returns 5
true + "bar" // concatenates the boolean value and returns "truebar"
5 + "foo" // concatenates the string and the number and returns "5foo"
"foo" + "bar" // concatenates the strings and returns "foobar"
_Hint:_ There is a handy <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment_(' target='_blank' rel='nofollow'>increment</a>) operator that is a great shortcut when you're adding numbers by 1.
## Subtraction
**Syntax**
`a - b`
**Usage**
2 - 3 // returns -1
3 - 2 // returns 1
false - 5 // interprets false as 0 and returns -5
true - 3 // interprets true as 1 and returns -2
5 - "foo" // returns NaN (Not a Number)
_Hint:_ There is a handy <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Decrement_(--' target='_blank' rel='nofollow'>decrement</a>) operator that is a great shortcut when you're subtracting numbers by 1.
## Multiplication
**Syntax**
`a * b`
**Usage**
2 * 3 // returns 6
3 * -2 // returns -6
false * 5 // interprets false as 0 and returns 0
true * 3 // interprets true as 1 and returns 3
5 * "foo" // returns NaN (Not a Number)
Infinity * 0 // returns NaN
Infinity * Infinity // returns Infinity
## Division
**Syntax**
`a / b`
**Usage**
3 / 2 // returns 1.5
3.0 / 2/0 // returns 1.5
3 / 0 // returns Infinity
3.0 / 0.0 // returns Infinity
-3 / 0 // returns -Infinity
false / 5 // interprets false as 0 and returns 0
true / 2 // interprets true a 1 and returns 0.5
5 / "foo" // returns NaN (Not a Number)
Infinity / Infinity // returns NaN
## Remainder
**Syntax**
`a % b`
**Usage**
3 % 2 // returns 1
true % 5 // interprets true as 1 and returns 1
false % 4 // interprets false as 0 and returns 0
3 % "bar" // returns NaN
## Increment
**Syntax**
`a++ or ++a`
**Usage**
// Postfix
x = 3; // declare a variable
y = x++; // y = 4, x = 3
// Prefix
var a = 2;
b = ++a; // a = 3, b = 3
## Decrement
**Syntax**
`a-- or --a`
**Usage**
// Postfix
x = 3; // declare a variable
y = x--; // y = 3, x = 3
// Prefix
var a = 2;
b = --a; // a = 1, b = 1
_!Important!_ As you can see, you **cannot** perform any sort of operations on `Infinity`.
Source: The amazing <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators' target='_blank' rel='nofollow'>MDN</a>.

View File

@ -0,0 +1,83 @@
---
title: Arrow Functions
---
Arrow functions are a new ES6 syntax for writing JavaScript function expressions. The shorter syntax saves time, as well as simplifying the function scope.
## What are arrow functions?
An arrow function expression is a more concise syntax for writing function expressions using a "fat arrow" token (`=>`).
### The basic syntax
Below is a basic example of an arrow function:
```javascript
// ES5 syntax
var multiply = function(x, y) {
return x * y;
};
// ES6 arrow function
var multiply = (x, y) => { return x * y; };
// Or even simpler
var multiply = (x, y) => x * y;
```
You no longer need the `function` and `return` keywords, or even the curly brackets.
```javascript
// everything included
const multiply = function(x, y) => { return x * y };
// remove "function"
const multiply = (x, y) => { return x * y };
// remove curly brackets and "return" ==> this way it returns implicitly
const multiply = (x, y) => x * y;
// if you only have one argument/parameter
const multiplyBy2 = x => x * 2;
// combined with the ternary operator, but note it's not a looker!
const addOrMultiply = (x, y, mathOperator) => mathOperator.toLowerCase() === 'add' ? x + y : x * y;
```
### A simplified `this`
Before arrow functions, new functions defined their own `this` value. To use `this` inside a traditional function expression, we have to write a workaround like so:
```javascript
// ES5 syntax
function Person() {
// we assign `this` to `self` so we can use it later
var self = this;
self.age = 0;
setInterval(function growUp() {
// `self` refers to the expected object
self.age++;
}, 1000);
}
```
An arrow function doesn't define it's own `this` value, it inherits `this` from the enclosing function:
```javascript
// ES6 syntax
function Person(){
this.age = 0;
setInterval(() => {
// `this` now refers to the Person object, brilliant!
this.age++;
}, 1000);
}
var p = new Person();
```
#### Further Reading
<a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions' target='_blank' rel='nofollow'>MDN link</a>

View File

@ -0,0 +1,63 @@
---
title: Assignment Operators
---
# Assignment Operators
Assignment operators, as the name suggests, assign (or re-assign) values to a variable. While there are quite a few variations on the assignment operators, they all build off of the basic assignment operator.
## Syntax
`x = y;` | Description | Necessity
:---------:|:---------------------:|:---------:
`x` | Variable | Required
`=` | Assignment operator | Required
`y` | Value to assign to variable | Required
## Examples
let initialVar = 5; // Variable initialization requires the use of an assignment operator
let newVar = 5;
newVar = 6; // Variable values can be modified using an assignment operator
## Variations
The other assignment operators are a shorthand for performing some operation using the variable (indicated by x above) and value (indicated by y above) and then assigning the result to the variable itself.
For example, below is the syntax for the addition assignment operator:
x += y;
This is the same as applying the addition operator and reassigning the sum to the original variable (i.e., x), which can be expressed by the following code:
x = x + y;
To illustrate this using actual values, here is another example of using the addition assignment operator:
let myVar = 5; // value of myVar: 5
myVar += 7; // value of myVar: 5 + 7 = 12
## Complete list of Javascript's assignment operators
Operator | Syntax | Long version
------------------------------- | --------- | -------------
Assignment | x = y | x = y
Addition assignment | x += y | x = x + y
Subtraction assignment | x -= y | x = x - y
Multiplication assignment | x *= y | x = x * y
Division assignment | x /= y | x = x / y
Remainder assignment | x %= y | x = x % y
Exponentiation assignment | x **= y | x = x ** y
Left shift assignment | x <<= y | x = x << y
Right shift assignment | x >>= y | x = x >> y
Unsigned right shift assignment | x >>>= y | x = x >>> y
Bitwise AND assignment | x &= y | x = x & y
Bitwise XOR assignment | x ^= y | x = x ^ y
Bitwise OR assignment | x |= y | x = x | y
### More Information:
<a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Assignment' target='_blank' rel='nofollow'>MDN link</a>
<a href='https://docs.microsoft.com/en-us/scripting/javascript/reference/assignment-operator-decrement-equal-javascript' target='_blank' rel='nofollow'>MSDN link</a>

View File

@ -0,0 +1,128 @@
---
title: Async messaging with RabbitMQ and Tortoise
---
RabbitMQ happens to be the easiest and most performant message broker platforms using the AMQ protocol out there today. Using it in a microservice architecture translates into massive performance gains, as well as the promise of reliability. In this guide, we're going to explore the basics of using RabbitMQ with Node.js.
## Theory
At its most basic level, you'd ideally have two different services interacting with one another through Rabbit - a _publisher_ and a _subscriber_. A publisher typically pushes messages to Rabbit, and a subscriber listens to these messages, and executes code on the basis of those messages. Note that they can be both at the same time - a service can publish messages to Rabbit and consume messages at the same time, which makes for really powerful systems to be designed.
Now a publisher typically publishes messages with a _routing key_ to something called an _exchange_. A consumer listens to a _queue_ on the same exchange, bound to the routing key. In architectural terms, your platform would use one Rabbit exchange, and different kinds of jobs/services would have their own routing keys and queues, for pub-sub to work effectively. Messages can be strings; they can also be native objects - AMQP client libraries do the heavy lifting of converting objects from one language to another. And yes, that does mean services can be written in different languages, so long as they're able to understand AMQP.
## Getting started
We're going to cook up a very simple example where a publisher script publishes a message to Rabbit, containing a URL, and a consumer script listens to Rabbit, takes the published URL, calls it and displays the results. You can find the finished sample up on [Github](https://github.com/rudimk/freecodecamp-guides-rabbitmq-tortoise).
First, let's initialize a npm project:
`$ npm init`
You can always just hit `Enter` all the way and use the default options - or you can fill them up. Now, let's install the packages we need. We're going to use [Tortoise](https://www.npmjs.com/package/tortoise), to interact with RabbitMQ. We're also going to use [node-cron](https://www.npmjs.com/package/node-cron), to schedule the actual message publishing.
`$ npm install --save tortoise node-cron`
Now your `package.json` should look a lot like this:
```
{
"name": "freecodecamp-guides-rabbitmq-tortoise",
"version": "1.0.0",
"description": "Sample code to accompany the FreeCodeCamp guide on async messaging with RabbitMQ and Tortoise.",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/rudimk/freecodecamp-guides-rabbitmq-tortoise.git"
},
"keywords": [
"rabbitmq",
"tortoise",
"amqp"
],
"author": "Rudraksh M.K.",
"license": "MIT",
"bugs": {
"url": "https://github.com/rudimk/freecodecamp-guides-rabbitmq-tortoise/issues"
},
"homepage": "https://github.com/rudimk/freecodecamp-guides-rabbitmq-tortoise#readme",
"dependencies": {
"node-cron": "^1.2.1",
"tortoise": "^1.0.1"
}
}
```
Now we're all set. Let's create a publisher first.
```javascript
const Tortoise = require('tortoise')
const cron = require('node-cron')
const tortoise = new Tortoise(`amqp://rudimk:YouKnowWhat@$localhost:5672`)
```
After importing `tortoise` and `node-cron`, we've gone ahead and initialized a connection to RabbitMQ. Next, let's write a quick and dirty function that publishes a message to Rabbit:
```javascript
function scheduleMessage(){
let payload = {url: 'https://randomuser.me/api'}
tortoise
.exchange('random-user-exchange', 'direct', { durable:false })
.publish('random-user-key', payload)
}
```
That's simple enough. We've defined a dictionary containing a URL to the [RandomUser.me](https://randomuser.me/) API, which is then published to the `random-user-exchange` exchange on RabbitMQ, with the `random-user-key` routing key. As mentioned earlier, the routing key is what determines who gets to consume a message. Now, let's write a scheduling rule, to publish this message every 60 seconds.
```javascript
cron.schedule('60 * * * * *', scheduleMessage)
```
And our publisher's ready! But it's really no good without a consumer to actually consume these messages! But first, we do need a library that can call the URL in these messages. Personally, I use `superagent`: `npm install --save superagent`.
Now, in `consumer.js`:
```javascript
const Tortoise = require('tortoise')
const superagent = require('superagent')
const tortoise = new Tortoise(`amqp://rudimk:YouKnowWhat@$localhost:5672`)
```
Next, let's write an async function that calls a URL and displays the result:
```javascript
async function getURL(url){
let response = await superagent.get(url)
return response.body
}
```
Time to write code to actually consume messages:
```javascript
tortoise
.queue('random-user-queue', { durable: false })
// Add as many bindings as needed
.exchange('random-user-exchange', 'direct', 'random-user-key', { durable: false })
.prefetch(1)
.subscribe(function(msg, ack, nack) {
// Handle
let payload = JSON.parse(msg)
getURL(payload['url']).then((response) => {
console.log('Job result: ', response)
})
ack() // or nack()
})
```
Here, we've told `tortoise` to listen to the `random-user-queue`, that's bound to the `random-user-key` on the `random-user-exchange`. Once a message is received, the payload is retrieved from `msg`, and is passed along to the `getURL` function, which in turn returns a Promise with the desired JSON response from the RandomUser API.
## Conclusion
The simplicity associated with using RabbitMQ for messaging is unparalleled, and it's very easy to come up with really complex microservice patterns, with just a few lines of code. The best part is that the logic behind messaging doesn't really change across languages - Crystal or Go or Python or Ruby work with Rabbit in pretty much the same way - this means you can have services written in different languages all communicating with each other effortlessly, enabling you to use the best language for the job.

View File

@ -0,0 +1,118 @@
---
title: Await Promises
---
## Await Promises
The `async` / `await` <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators' target='_blank' rel='nofollow'>operators</a> make it easier to implement many async Promises. They also allow engineers to write clearer, more succinct, testable code.
To understand this subject, you should have a solid understanding of how <a href='https://guide.freecodecamp.org/javascript/promises' target='_blank' rel='nofollow'>Promises</a> work.
---
## Basic Syntax
``` javascript
function slowlyResolvedPromiseFunc(string) {
return new Promise(resolve => {
setTimeout(() => {
resolve(string);
}, 5000);
});
}
async function doIt() {
const myPromise = await slowlyResolvedPromiseFunc("foo");
console.log(myPromise); // "foo"
}
doIt();
```
There are a few things to note:
* The function that encompasses the `await` declaration must include the `async` operator. This will tell the JS interpreter that it must wait until the Promise is resolved or rejected.
* The `await` operator must be inline, during the const declaration.
* This works for `reject` as well as `resolve`.
---
## Nested Promises vs. `Async` / `Await`
Implementing a single Promise is pretty straightforward. In contrast, Chained Promises or the creation of a dependency pattern may produce "spaghetti code".
The following examples assume that the <a href='https://github.com/request/request-promise' target='_blank' rel='nofollow'>`request-promise`</a> library is available as `rp`.
### Chained/Nested Promises
``` javascript
// First Promise
const fooPromise = rp("http://domain.com/foo");
fooPromise.then(resultFoo => {
// Must wait for "foo" to resolve
console.log(resultFoo);
const barPromise = rp("http://domain.com/bar");
const bazPromise = rp("http://domain.com/baz");
return Promise.all([barPromise, bazPromise]);
}).then(resultArr => {
// Handle "bar" and "baz" resolutions here
console.log(resultArr[0]);
console.log(resultArr[1]);
});
```
### `async` and `await` Promises
``` javascript
// Wrap everything in an async function
async function doItAll() {
// Grab data from "foo" endpoint, but wait for resolution
console.log(await rp("http://domain.com/foo"));
// Concurrently kick off the next two async calls,
// don't wait for "bar" to kick off "baz"
const barPromise = rp("http://domain.com/bar");
const bazPromise = rp("http://domain.com/baz");
// After both are concurrently kicked off, wait for both
const barResponse = await barPromise;
const bazResponse = await bazPromise;
console.log(barResponse);
console.log(bazResponse);
}
// Finally, invoke the async function
doItAll().then(() => console.log('Done!'));
```
The advantages of using `async` and `await` should be clear. This code is more readable, modular, and testable.
It's fair to note that even though there is an added sense of concurrency, the underlying computational process is the same as the previous example.
---
## Handling Errors / Rejection
A basic try-catch block handles a rejected Promise.
``` javascript
async function errorExample() {
try {
const rejectedPromise = await Promise.reject("Oh-oh!");
} catch (error) {
console.log(error); // "Uh-oh!"
}
}
errorExample();
```
---
#### More Information:
* `await` Operator <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await' target='_blank' rel='nofollow'>MDN Docs</a>
* `async` Function Operator <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/async_function' target='_blank' rel='nofollow'>MDN Docs</a>

View File

@ -0,0 +1,103 @@
---
title: Boolean
---
## Boolean
Booleans are a primitive datatype commonly used in computer programming languages. By definition, a boolean has two possible values: `true` or `false`.
In Javascript, there is often implicit type coercion to boolean. If for example you have an if statement which checks a certain expression, that expression will be coerced to a boolean:
```javascript
var a = 'a string';
if (a) {
console.log(a); // logs 'a string'
}
```
There are only a few values that will be coerced to false:
- false (not really coerced as it already is false)
- null
- undefined
- NaN
- 0
- '' or "" (empty string)
All other values will be coerced to true.
When a value is coerced to a boolean, we also call that either 'falsy' or 'truthy'.
One way that type coercion is used is with the use of the or (`||`) and and (`&&`) operators:
```javascript
var a = 'word';
var b = false;
var c = true;
var d = 0
var e = 1
var f = 2
var g = null
console.log(a || b); // 'word'
console.log(c || a); // true
console.log(b || a); // 'word'
console.log(e || f); // 1
console.log(f || e); // 2
console.log(d || g); // null
console.log(g || d); // 0
console.log(a && c); // true
console.log(c && a); // 'word'
```
As you can see, the *or* operator checks the first operand. If this is true or truthy, it returns it immediately (which is why we get 'word' in the first case & true in the second case). If it is not true or truthy, it returns the second operand (which is why we get 'word' in the third case).
With the and operator it works in a similar way, but for 'and' to be true, both operands need to be truthy. So it will always return the second operand if both are true/truthy, otherwise it will return false. That is why in the fourth case we get true and in the last case we get 'word'.
## The Boolean Object
There is also a native JavaScript object that wraps around a value. The value passed as the first parameter is converted to a boolean value, if necessary. If value is omitted, 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false. All other values, including any object or the string "false", create an object with an initial value of true.
Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object.
## More Details
Any object whose value is not undefined or null, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement. If true, this will execute the function. For example, the condition in the following if statement evaluates to true:
```javascript
var x = new Boolean(false);
if (x) {
// this code is executed
}
```
This behavior does not apply to Boolean primitives. For example, the condition in the following if statement evaluates to false:
```javascript
var x = false;
if (x) {
// this code is not executed
}
```
Do not use a Boolean object to convert a non-boolean value to a boolean value. Instead, use Boolean as a function to perform this task:
```javascript
var x = Boolean(expression); // preferred
var x = new Boolean(expression); // don't use
```
If you specify any object, including a Boolean object whose value is false, as the initial value of a Boolean object, the new Boolean object has a value of true.
```javascript
var myFalse = new Boolean(false); // initial value of false
var g = new Boolean(myFalse); // initial value of true
var myString = new String('Hello'); // string object
var s = new Boolean(myString); // initial value of true
```
Do not use a Boolean object in place of a Boolean primitive.
### Resources
- <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean' target='_blank' rel='nofollow'>Boolean Object</a>
- <a href='https://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html' target='_blank' rel='nofollow'>Boolean Object</a>

View File

@ -0,0 +1,81 @@
---
title: Callback Functions
---
This article gives a brief introduction to the concept and usage of callback functions in the Javascript programming language.
## Functions are Objects
The first thing we need to know is that in Javascript, functions are first-class objects. As such, we can work with them in the same way we work with other objects, like assigning them to variables and passing them as arguments into other functions. This is important, because it's the latter technique that allows us to extend functionality in our applications.
## Callback Functions
A **callback function** is a function that is passed _as an argument_ to another function, to be "called back" at a later time. A function that accepts other functions as arguments is called a **higher-order function**, which contains the logic for _when_ the callback function gets executed. It's the combination of these two that allow us to extend our functionality.
To illustrate callbacks, let's start with a simple example:
```javascript
function createQuote(quote, callback){
var myQuote = "Like I always say, " + quote;
callback(myQuote); // 2
}
function logQuote(quote){
console.log(quote);
}
createQuote("eat your vegetables!", logQuote); // 1
// Result in console:
// Like I always say, eat your vegetables!
```
In the above example, `createQuote` is the higher-order function, which accepts two arguments, the second one being the callback. The `logQuote` function is being used to pass in as our callback function. When we execute the `createQuote` function _(1)_, notice that we are _not appending_ parentheses to `logQuote` when we pass it in as an argument. This is because we do not want to execute our callback function right away, we simply want to pass the function definition along to the higher-order function so that it can be executed later.
Also, we need to ensure that if the callback function we pass in expects arguments, that we supply those arguments when executing the callback _(2)_. In the above example, that would be the `callback(myQuote);` statement, since we know that `logQuote` expects a quote to be passed in.
Additionally, we can pass in anonymous functions as callbacks. The below call to `createQuote` would have the same result as the above example:
```javascript
createQuote("eat your vegetables!", function(quote){
console.log(quote);
});
```
Incidentally, you don't _have_ to use the word "callback" as the name of your argument, Javascript just needs to know that it's the correct argument name. Based on the above example, the below function will behave in exactly the same manner.
```javascript
function createQuote(quote, functionToCall) {
var myQuote = "Like I always say, " + quote;
functionToCall(myQuote);
}
```
## Why use Callbacks?
Most of the time we are creating programs and applications that operate in a **synchronous** manner. In other words, some of our operations are started only after the preceding ones have completed. Often when we request data from other sources, such as an external API, we don't always know _when_ our data will be served back. In these instances we want to wait for the response, but we don't always want our entire application grinding to a halt while our data is being fetched. These situations are where callback functions come in handy.
Let's take a look at an example that simulates a request to a server:
```javascript
function serverRequest(query, callback){
setTimeout(function(){
var response = query + "full!";
callback(response);
},5000);
}
function getResults(results){
console.log("Response from the server: " + results);
}
serverRequest("The glass is half ", getResults);
// Result in console after 5 second delay:
// Response from the server: The glass is half full!
```
In the above example, we make a mock request to a server. After 5 seconds elapse the response is modified and then our callback function `getResults` gets executed. To see this in action, you can copy/paste the above code into your browser's developer tool and execute it.
Also, if you are already familiar with `setTimeout`, then you've been using callback functions all along. The anonymous function argument passed into the above example's `setTimeout` function call is also a callback! So the example's original callback is actually executed by another callback. Be careful not to nest too many callbacks if you can help it, as this can lead to something called "callback hell"! As the name implies, it isn't a joy to deal with.
Please refer to this link for more details on "callback hell" : http://callbackhell.com/

View File

@ -0,0 +1,183 @@
---
title: Classes
---
## Classes
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
JavaScript does not have the concept of classes inherently.
But we could simulate the functionalities of a class by taking advantage of the prototypal nature of JavaScript.
This article assumes that you have a basic understanding of <a href="/src/pages/javascript/prototypes/index.md">prototypes</a>.
For the sake of clarity let us assume that we want to create a class which can do the following
```javascript
var p = new Person('James','Bond'); // create a new instance of Person class
p.log() // Output: 'I am James Bond' // Accessing a function in the class
// Using setters and getters
p.profession = 'spy'
p.profession // output: James bond is a spy
```
### Using class keyword
Like in any other programming language, you can now use the `class` keyword to create a class.
This is not supported in older browsers and was introduced in ECMAScript 2015.
```javascript
class Person {
constructor(firstName, lastName) {
this._firstName = firstName;
this._lastName = lastName;
}
log() {
console.log('I am', this._firstName, this._lastName);
}
// setters
set profession(val) {
this._profession = val;
}
// getters
get profession() {
console.log(this._firstName, this._lastName, 'is a', this._profession);
}
}
```
<br />
<br />
`class` is just a syntactic sugar over JavaScript's existing prototype-based inheritance model.
In general programmers use the following ways to create a class in JavaScript.
### Using methods added to prototypes:
Here, all the methods are added to prototype
```javascript
function Person(firstName, lastName) {
this._firstName = firstName;
this._lastName = lastName;
}
Person.prototype.log = function() {
console.log('I am', this._firstName, this._lastName);
}
// This line adds getters and setters for the profession object. Note that in general you could just write your own get and set functions like the 'log' method above.
// Since in this example we are trying the mimic the class above, we try to use the getters and setters property provided by JavaScript
Object.defineProperty(Person.prototype, 'profession', {
set: function(val) {
this._profession = val;
},
get: function() {
console.log(this._firstName, this._lastName, 'is a', this._profession);
}
})
```
You could also write prototype methods over function `Person` as below
```javascript
Person.prototype = {
log: function() {
console.log('I am ', this._firstName, this._lastName);
}
set profession(val) {
this._profession = val;
}
get profession() {
console.log(this._firstName, this._lastName, 'is a', this._profession);
}
}
```
### Using methods added internally
Here the methods are added internally instead of prototype
```javascript
function Person(firstName, lastName) {
this._firstName = firstName;
this._lastName = lastName;
this.log = function() {
console.log('I am ', this._firstName, this._lastName);
}
Object.defineProperty(this, 'profession', {
set: function(val) {
this._profession = val;
},
get: function() {
console.log(this._firstName, this._lastName, 'is a', this._profession);
}
})
}
```
### Hiding details in classes with symbols
Most often some properties and methods have to be hidden to prevent access from outside the function. With classes, to obtain this functionality, one way to do this is by using symbols. Symbol is a new built-in type of JavaScript, which can be invoked to give a new symbol value. Every Symbol is unique and can be used as a key on object. So one use case of symbols is that you can add something to an object you might not own, and you might not want to collide with any other keys of object so creating a new one and adding as property to that object using symbol is the safest. Also, when symbol value is added to an object; no one else will know how to get it.
```javascript
class Person {
constructor(firstName, lastName) {
this._firstName = firstName;
this._lastName = lastName;
}
log() {
console.log('I am', this._firstName, this._lastName);
}
// setters
set profession(val) {
this._profession = val;
}
// getters
get profession() {
console.log(this._firstName, this._lastName, 'is a', this._profession);
}
// With the above code, even though we can access the properties outside the function to change their content what if we don't want that.
// Symbols come to rescue.
let s_firstname = new Symbol();
class Person {
constructor(firstName, lastName) {
this[s_firstName] = firstName;
this._lastName = lastName;
}
log() {
console.log('I am', this._firstName, this._lastName);
}
// setters
set profession(val) {
this._profession = val;
}
// getters
get profession() {
console.log(this[s_firstName], this._lastName, 'is a', this._profession);
}
```
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -0,0 +1,179 @@
---
title: Closures
---
# Closures
A closure is the combination of a function and the lexical environment (scope) within which that function was declared. Closures are a fundamental and powerful property of Javascript. This article discusses the 'how' and 'why' about Closures:
### Example
```js
//we have an outer function named walk and an inner function named fly
function walk (){
var dist = '1780 feet';
function fly(){
console.log('At '+dist);
}
return fly;
}
var flyFunc = walk(); //calling walk returns the fly function which is being assigned to flyFunc
//you would expect that once the walk function above is run
//you would think that JavaScript has gotten rid of the 'dist' var
flyFunc(); //Logs out 'At 1780 feet'
//but you still can use the function as above
//this is the power of closures
```
### Another Example
```js
function by(propName) {
return function(a, b) {
return a[propName] - b[propName];
}
}
const person1 = {name: 'joe', height: 72};
const person2 = {name: 'rob', height: 70};
const person3 = {name: 'nicholas', height: 66};
const arr_ = [person1, person2, person3];
const arr_sorted = arr_.sort(by('height')); // [ { name: 'nicholas', height: 66 }, { name: 'rob', height: 70 },{ name: 'joe', height: 72 } ]
```
The closure 'remembers' the environment in which it was created. This environment consists of any local variables that were in-scope at the time the closure was created.
```js
function outside(num) {
var rememberedVar = num; // In this example, rememberedVar is the lexical environment that the closure 'remembers'
return function inside() { // This is the function which the closure 'remembers'
console.log(rememberedVar)
}
}
var remember1 = outside(7); // remember1 is now a closure which contains rememberedVar = 7 in its lexical environment, and //the function 'inside'
var remember2 = outside(9); // remember2 is now a closure which contains rememberedVar = 9 in its lexical environment, and //the function 'inside'
remember1(); // This now executes the function 'inside' which console.logs(rememberedVar) => 7
remember2(); // This now executes the function 'inside' which console.logs(rememberedVar) => 9
```
Closures are useful because they let you 'remember' data and then let you operate on that data through returned functions. This allows javascript to emulate private methods that are found in other programming languages. Private methods are useful for restricting access to code as well as managing your global namespace.
### Private variables and methods
Closures can also be used to encapsulate private data/methods. Take a look at this example:
```javascript
const bankAccount = (initialBalance) => {
const balance = initialBalance;
return {
getBalance: function() {
return balance;
},
deposit: function(amount) {
balance += amount;
return balance;
},
};
};
const account = bankAccount(100);
account.getBalance(); // 100
account.deposit(10); // 110
```
In this example, we won't be able to access `balance` from anywhere outside of the `bankAccount` function, which means we've just created a private variable. Where's the closure? Well, think about what `bankAccount()` is returning. It actually returns an Object with a bunch of functions inside it, and yet when we call `account.getBalance()`, the function is able to "remember" its initial reference to `balance`. That is the power of the closure, where a function "remembers" its lexical scope (compile time scope), even when the function is executed outside that lexical scope.
<b>Emulating block-scoped variables.</b>
Javascript did not have a concept of block-scoped variables. Meaning that when defining a variable inside a forloop for example, this variable is visible from outside the forloop as well. So how can closures help us solve this problem ? Let's take a look.
```javascript
var funcs = [];
for(var i = 0; i < 3; i++){
funcs[i] = function(){
console.log('My value is ' + i); //creating three different functions with different param values.
}
}
for(var j = 0; j < 3; j++){
funcs[j](); // My value is 3
// My value is 3
// My value is 3
}
```
Since the variable i does not have block-scope, it's value within all three functions was updated with the loop counter and created malicious values. Closure can help us solve this issue by creating a snapshot of the environment the function was in when it was created, preserving its state.
```javascript
var funcs = [];
var createFunction = function(val){
return function() {console.log("My value: " + val);};
}
for (var i = 0; i < 3; i++) {
funcs[i] = createFunction(i);
}
for (var j = 0; j < 3; j++) {
funcs[j](); // My value is 0
// My value is 1
// My value is 2
}
```
The late versions of javascript es6+ have a new keyword called let which can be used to give the variable a blockscope.
There are also many functions (forEach) and entire libraries (lodash.js) that are dedicated to solve such problems as the ones explained above. They can certainly boost your productivity, however it remains extremely important to have knowledge of all these issues when attempting to create something big.
Closures have many special applications that are useful when creating large javascript programs.
1. Emulating private variables or encapsulation
2. Making Asynchronous server side calls
3. Creating a block-scoped variable.
<b>Emulating private variables.</b>
Unlike many other languages, Javascript does not have a mechanism which allows you to create encapsulated instance variables within an object. Having public instance variables can cause a lot of problems when building medium to large programs. However with closures, this problem can be mitigated.
Much like in the previous example, you can build functions which return object literals with methods that have access to the object's local variables without exposing them. Thus, making them effectively private.
Closures can also help you manage your global namespace to avoid collisions with globally shared data. Usually all global variables are shared between all scripts in your project, which will definitely give you alot of trouble when building medium to large programs. That is why library and module authors use closures to hide an entire module's methods and data. This is called the module pattern, it uses an immediately invoked function expression which exports only certain functionality to the outside world, significantly reducing the amount of global references.
Here's a short sample of a module skeleton.
```javascript
var myModule = (function() = {
let privateVariable = 'I am a private variable';
let method1 = function(){ console.log('I am method 1'); };
let method2 = function(){ console.log('I am method 2, ', privateVariable); };
return {
method1: method1,
method2: method2
}
}());
myModule.method1(); // I am method 1
myModule.method2(); // I am method 2, I am a private variable
```
Closures are useful for capturing new instances of private variables contained in the 'remembered' environment, and those variables can only be accessed through the returned function or methods.
### More Information:
<a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures' target='_blank' rel='nofollow'>MDN</a>
<br />
<a href='https://medium.freecodecamp.org/lets-learn-javascript-closures-66feb44f6a44' target='_blank' rel='nofollow'>Javascript Closures</a>

View File

@ -0,0 +1,31 @@
---
title: Code Block
---
## Introduction
In computer programming, a **block** or code **block** is a section of code which is grouped together. Blocks consist of one or more declarations and statements. A programming language that permits the creation of blocks, including blocks nested within other blocks, is called a block-structured programming language. JavaScript is one such programming language.
A **block** statement in JavaScript is used to group zero or more statements. The block is delimited by a pair of curly brackets.
{
statement_1;
statement_2;
...
statement_n;
}
<a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block' target='_blank' rel='nofollow'>MDN link</a>
## Examples
The **block** statement is commonly used with control flow statements (e.g. `if...else`, `for`, `while`) and functions.
while (x < 10) {
x++;
}
function addnums(num1, num2) {
var sum = 0;
sum = num1 + num2;
return sum;
}

View File

@ -0,0 +1,24 @@
---
title: Code Linting
---
Linting is the process of running a program that analyzes your code for programmatic and stylistic errors. A linting tool, or a linter, marks or flags any potential errors in your code such as syntax errors or incorrectly spelled variable names. This can save time and help you write better code.
Linters can be installed using `npm` or another package manager. Linters can be used from the command line by passing in files. Linters are also available as plugins for tools and sometimes they are directly integrated into editors.
Here are some popular Javascript Linters:
[JSLint](http://www.javascriptlint.com/online_lint.php)
[JSHint](http://jshint.com)
[JSCS](http://jscs.info)
[ESLint](http://eslint.org)
#### Linters for Editors :
* Visual Code : To Install the eslint extension, open command palette (View -> Command Palette.. or cmd+shift+p ) and execute command:
ext install eslint
#### Tools and Plugins
[Prettier](https://prettier.io)

View File

@ -0,0 +1,82 @@
---
title: Comments
---
## Comments
Programmers use comments to add hints, notes, suggestions, or warnings to their source code; they have no effect on the actual output of the code. Comments can be very helpful in explaining the intent of what your code is or should be doing.
It is always best practice when starting out to comment more often than not, as it can help those reading your code to understand what exactly your code is intending to do.
JavaScript has two ways of assigning comments in its code.
The first way is the `//` comment; all text following `//` on the same line into a comment. For example:
```javascript
function hello() {
// This is a one line JavaScript comment
console.log("Hello world!");
}
hello();
```
The second way is the `/* */` comment, which can be used for both single-line and multi-line comments. For example:
```javascript
function hello() {
/* This is a one line JavaScript comment */
console.log("Hello world!");
}
hello();
```
```javascript
function hello() {
/* This comment spans multiple lines. Notice
that we don't need to end the comment until we're done. */
console.log("Hello world!");
}
hello();
```
You can also prevent execution of Javascript code just commeting the code lines like this:
```javascript
function hello() {
/*console.log("Hello world!");*/
}
hello();
```
#### More Information:
<a href='https://www.digitalocean.com/community/tutorials/how-to-write-comments-in-javascript' target='_blank' rel='nofollow'>How To Write Comments in JavaScript</a>
<h3>Many IDEs come with a keyboard shortcut to comment out lines. </h3>
<ol>
<li>Highlight text to be commented</li>
<li>Mac: Push Command(Apple Key) & "/"</li>
<li>Windows: Push Control & "/"</li>
<li>You can also uncomment code by doing the same steps</li>
</ol>
A shortcut to comment out a section of javascript in many code editors is to highlight the lines of code you want to comment out, then press `Cmd/Ctrl + /`.
Comments are also very helpful for code testing as you can prevent a certain code-line/block from running
```javascript
function hello() {
// The statement below is not going to get executed
// console.log('hi')
}
hello();
```
```
function hello() {
// The statements below are not going to get executed
/*
console.log('hi');
console.log('code-test');
*/
}
hello();
```
#### More Information:
* <a href='https://www.digitalocean.com/community/tutorials/how-to-write-comments-in-javascript' target='_blank' rel='nofollow'>How To Write Comments in JavaScript</a>

View File

@ -0,0 +1,194 @@
---
title: Comparison Operators
---
JavaScript has both **strict** and **typeconverting** comparisons.
* A strict comparison (e.g. ===) is only true if the operands are of the same type.
* The more commonly used abstract comparison (e.g. ==) converts the operands to the same Type before making the comparison.
* For relational abstract comparisons (e.g., <=), the operands are first converted to primitives, then to the same type, before comparison.
* Strings are compared based on standard lexicographical ordering, using Unicode values.
## Features of comparisons:
* Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
* Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another.
* Two Boolean operands are strictly equal if both are true or both are false.
* Two distinct objects are never equal for either strict or abstract comparisons.
* An expression comparing Objects is only true if the operands reference the same Object.
* Null and Undefined Types are strictly equal to themselves and abstractly equal to each other.
## Equality operators
### Equality (==)
The equality operator converts the operands if they are **not of the same type**, then applies strict comparison. If **both operands are objects**, then JavaScript compares internal references which are equal when operands refer to the same object in memory.
#### Syntax
x == y
#### Examples
1 == 1 // true
"1" == 1 // true
1 == '1' // true
0 == false // true
0 == null // false
0 == undefined // false
null == undefined // true
### Inequality (!=)
The inequality operator returns true if the operands are not equal. If the two operands are **not of the same type**, JavaScript attempts to convert the operands to an appropriate type for the comparison. If **both operands are objects**, then JavaScript compares internal references which are not equal when operands refer to different objects in memory.
#### Syntax
x != y
#### Examples
1 != 2 // true
1 != "1" // false
1 != '1' // false
1 != true // false
0 != false // false
### Identity / strict equality (===)
The identity operator returns true if the operands are strictly equal **with no type conversion**.
#### Syntax
x === y
#### Examples
3 === 3 // true
3 === '3' // false
### Non-identity / strict inequality (!==)
The non-identity operator returns true if the operands **are not equal and/or not of the same type**.
#### Syntax
x !== y
#### Examples
3 !== '3' // true
4 !== 3 // true
## Relational operators
### Greater than operator (>)
The greater than operator returns true if the left operand is greater than the right operand.
#### Syntax
x > y
#### Examples
4 > 3 // true
### Greater than or equal operator (>=)
The greater than or equal operator returns true if the left operand is greater than or equal to the right operand.
#### Syntax
x >= y
#### Examples
4 >= 3 // true
3 >= 3 // true
### Less than operator (<)
The less than operator returns true if the left operand is less than the right operand.
#### Syntax
x < y
#### Examples
3 < 4 // true
### Less than or equal operator (<=)
The less than or equal operator returns true if the left operand is less than or equal to the right operand.
#### Syntax
x <= y
#### Examples
3 <= 4 // true
_You can find more information at <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators' target='_blank' rel='nofollow'>MDN</a>._
## Comparing null and undefined
When we compare null and undefined we see different behaviour. Lets check different scenario through examples
#### Example - strict equality check (===)
```javascript
console.log( null === undefined ); // O/P - false
```
Otuput is false and that's correct because we know "null" and "undefined" are different types.
#### Example - non-strict equality check (==)
```javascript
console.log( null == undefined ); // O/P: - true
```
How? This is because there is a special rule for "null" and "undefined". Due to which they are equal in case of non-strict check (==) but are not equal to any other value.
If we use comparison operators like <, >, <=, >= etc., "null" and "undefined" are converted to number and in such cases "null" will become 0 and "undefined" will be NaN. Lets check some of those examples.
#### Example - compare null with 0(zero)
```javascript
console.log( null > 0 ); // O/P - false
console.log( null >= 0 ); // O/P - true
console.log( null == 0 ); // O/P - false
```
Strange? As per the first statement null is not greater than 0 and from the second statement null is either greater than or equal to 0. So, if we think mathematically and compare both statements, will come to the result that null is equal to 0. But, as per third statement it's not true. Why?
The reason is "comparison" and "equality check" both works in different way.
In comparison, "null/undefined" is first converted to number so, in first two cases "null" become 0 and hence case1) (null > 0) -> false and case2) (null >= 0) -> true.
But, in equality check (==), "null/undefined" works without any conversion and as explained above (special rule), in equality check "null/undefined" are only equal to each other and are not equal to anything else. Hence (null == 0) -> false.
#### Example - compare undefined with 0(zero)
```javascript
console.log( undefined > 0 ); // O/P - false
console.log( undefined >= 0 ); // O/P - false
console.log( undefined == 0 ); // O/P - false
```
Here, we test the same cases as we did for null but again result is different. Why?
The reasons are as follow.
In first two cases, we are comparing undefined with 0 and as mentioned above in comparison undefined gets converted to NaN. NaN is a special value which always return false when compared with any number and that's why we got false as output in first two cases.
For third statement, reason is same as mentioned for "null". In equality check "null/undefined" are only equal to each other and not equal to anything else. Hence (undefined == 0) -> false.

View File

@ -0,0 +1,69 @@
---
title: Concurrency Model and Event Loop
---
## Concurrency Model and Event Loop
Javascript runtime is single threaded which means that it can execute one piece of code at a time. In order to understand the concurrency model and the event loop in Javascript we have to first get around with some common terms that are associated with it. First let's learn what is a call stack.
A call stack is a simple data structure that records where in the code we are currently. So if we step into a function that is a function invocation it is pushed to the call stack and when we return from a function it is popped out of the stack.
Let's take a code example to understand the call stack-
```javascript
function multiply(x,y) {
return x * y;
}
function squared(n) {
return multiply(n,n)
}
function printSquare(n) {
return squared(n)
}
let numberSquared = printSquare(5);
console.log(numberSquared);
```
First when the code executes the runtime will read through each of the function definitions but when it reaches the line where the first function **printSquare(5)** is invoked it will push this function into the call stack. Next, this function will execute and before returning it will encounter another function **squared(n)** so it will suspend it's current operation and push this function on top of the existing function. It executes the function in this case the squared function and finally it encounters another function **multiply(n,n)** hence it suspends its current executions and pushes this function into the call stack.The function
multiply executes and it returns with the multiplied value. Finally the squared function returns and is popped off the stack and then the same goes with printSquare. The final squared value is allocated to the numberSquared variable.We encounter again a function invocation in this case it's a console.log() statement so the runtime pushes this to the stack which executes it thus printing the squared number on the console. It should be noted that the first function that gets pushed into the stack before any of the above code runs is the main function which in the runtime is denoted as an 'anonymous function'.
So to summarize whenever a function is invoked it is pushed into the call stack where it executes. Finally when the function is done with it's execution and is returning either implicitly or explicitly it will be popped off the stack. The call stack just records at what point in time which funciton was executing. It keeps track of which function is currently executing.
Now we know from this that Javascript can execute one thing at a time but that's not the case with the Browser. The Browser has it's own set of API's like setTimeout, XMLHttpRequests which are not specified in the Javascript runtime. In fact if you look through the source code of V8, the popular Javascript runtime that powers browsers like Google Chrome you won't find any definitions for it. It's because these special web API's exist in the browser environment not inside the javascript environment and you can say that these apis introduces concurrency into the mix. Let's look at a diagram to understand the whole picture.
![Concurrency and Event Loop Model](https://i.imgur.com/rnQEY7o.png)
Some more terms are introduced
**Heap**- It's mostly the place where objects are allocated.
**Callback Queue**- It's a data structure that stores all the callbacks. Since it's a queue so the elements are processed based on FIFO which is First in First Out.
**Event Loop**- This is where all these things come together. What the event loop simply does is it checks the call stacks and if it is empty which means there are no functions in the stack it takes the oldest callback from
the callback queue and pushes it into the call stack which eventually executes the callback.
Let's understand this with a code example-
```javascript
console.log('hi');
setTimeout(function() {
console.log('freecodeCamp')
},5000);
console.log('JS')
```
When the first line executes it's a console.log() which is a function invocation which means that this function is pushed into the call stack where it executes printing 'hi' to the console and finally it's returned and is popped off the stack. Then when the runtime goes to executes setTimeout() it knows that this is a web API and hence it gives it off to the browser to handle it's execution. The browser starts the timer and then JS runtime pops the setTimeout() out of the stack. It encounters another console.log() invocation and so it pushes this into the call stack the message 'JS' is logged into the console and then it's finally returned and so the last console.log() is popped off the stack. Now the call stack is empty. Meanwhile while all of this was going on the timer finishes that is when 5 seconds have elapsed the browser goes ahead and pushes the callback function into the callback queue. Next the event loop checks if the call stack is free or not. Since it is free it takes the callback function and pushes it again back to the call stack which executes the code inside it. Again inside the code there is a console.log() invocation so this function goes to the top of the stack executes which logs 'freecodecamp' into the console and finally it returns which means it gets poppped off the stack and finally the callback gets popped of the stack and we are done.
To visualize this better try this tool by Phillip Roberts- [Loupe Event Loop Visualizer](http://latentflip.com/loupe/?code=!!!PGJ1dHRvbj5DbGljayBtZSE8L2J1dHRvbj4%3D)
#### More Information:
[Philip Roberts: What the heck is the event loop anyway? | JSConf EU 2014](https://www.youtube.com/watch?v=8aGhZQkoFbQ)
[Concurrency model and Event Loop MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop)

View File

@ -0,0 +1,27 @@
---
title: Conditional Ternary Operators
---
## Conditional Ternary Operators
### Basic usage
The ternary operator is a compact way to write an if-else inside an expression.
```js
const thing = (condition) ? <if true> : <if false>;
```
E.g.
```js
const cappedInput = input > 50 ? 50 : input // this will cap the input at 50
```
### Else if
You can also chain ternary operators, this way you will have an if-else if-else behaviour
```js
<first condition> ? <value if first true>
: <second condition> ? <value if second is true>
: <fallback value>
```
> **Pro tip**: As you see you can split the ternary operator on multiple lines
E.g.
```
const wealth = housesOwned > 3 ? "rich"
: housesOwned > 1 ? "nothing to complain"
: "poor"
```

View File

@ -0,0 +1,90 @@
---
title: Converting Strings to Numbers
---
## Converting Strings to Numbers
The `parseInt()` function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
```js
parseInt(string, radix);
```
### Parameters
string
The value to parse. If the `string` argument is not a string, then it is converted to a string (using the `ToString` abstract operation). Leading whitespace in the string argument is ignored.'=
radix
An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the above mentioned string. Specify `10` for the decimal numeral system commonly used by humans. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified, usually defaulting the value to 10.
Return value
An integer number parsed from the given string. If the first character cannot be converted to a number, `NaN` is returned.
### Description
The `parseInt` function converts its first argument to a string, parses it, and returns an integer or `NaN`. If not `NaN`, the returned value will be the integer that is the first argument taken as a number in the specified radix (base). For example, a radix of 10 indicates to convert from a decimal number, 8 octal, 16 hexadecimal, and so on. For radices above `10`, the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16),`A` through `F` is used.
If `parseInt` encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. `parseInt` truncates numbers to integer values. Leading and trailing spaces are allowed.
Because some numbers include the `e` character in their string representation (e.g. `6.022e23`), using `parseInt` to truncate numeric values will produce unexpected results when used on very large or very small numbers. `parseInt` should not be used as a substitute for `Math.floor()`.
If radix is `undefined` or 0 (or absent), JavaScript assumes the following:
* If the input `string` begins with "0x" or "0X", radix is 16 (hexadecimal) and the remainder of the string is parsed.
* If the input `string` begins with "0", radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason, always specify a radix when using parseInt.
* If the input `string` begins with any other value, the radix is 10 (decimal).
* If the first character cannot be converted to a number, parseInt returns NaN.
For arithmetic purposes, the NaN value is not a number in any radix. You can call the isNaN function to determine if the result of parseInt is NaN. If NaN is passed on to arithmetic operations, the operation results will also be NaN.
To convert the number to its string literal in a particular radix use intValue.toString(radix).
### Examples
Using `parseInt`
The following examples all return `15`:
```js
parseInt(' 0xF', 16);
parseInt(' F', 16);
parseInt('17', 8);
parseInt(021, 8);
parseInt('015', 10); // parseInt(015, 10); will return 15
parseInt(15.99, 10);
parseInt('15,123', 10);
parseInt('FXX123', 16);
parseInt('1111', 2);
parseInt('15 * 3', 10);
parseInt('15e2', 10);
parseInt('15px', 10);
parseInt('12', 13);
```
The following examples all return `NaN`:
```js
parseInt('Hello', 8); // Not a number at all
parseInt('546', 2); // Digits are not valid for binary representations
```
The following examples all return `-15`:
```js
parseInt('-F', 16);
parseInt('-0F', 16);
parseInt('-0XF', 16);
parseInt(-15.1, 10)
parseInt(' -17', 8);
parseInt(' -15', 10);
parseInt('-1111', 2);
parseInt('-15e1', 10);
parseInt('-12', 13);
```
The following examples all return `4`:
```js
parseInt(4.7, 10);
parseInt(4.7 * 1e22, 10); // Very large number becomes 4
parseInt(0.00000000000434, 10); // Very small number becomes 4
```
The following example returns `224`:
```js
parseInt('0e0', 16);
```
#### More Information:
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">parseInt on MDN</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt' target='_blank' rel='nofollow'>parseInt()</a> and <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat' target='_blank' rel='nofollow'>parseFloat()</a> attempt to convert the string to a number if possible. For example, `var x = parseInt("100"); // x = 100`
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/number' target='_blank' rel='nofollow'>Number()</a> will convert to a number the value can be represented by. This includes dates into the number of milliseconds since midnight January 1, 1970 UTC, boolean values to 1 or 0, and values that can't be converted to a recognisable number will become NaN. That stands for Not a Number and is also technically a number!

View File

@ -0,0 +1,151 @@
---
title: Error Handling and Try Catch Throw
---
## Error Handling and Try Catch Throw
The `try...catch..finally` statement marks a block of statements to try, and specifies a response, should an exception be thrown. The `try` statement contains one or more statements, and at least one `catch` clause or a `finally` clause, or both.
#### `try...catch`:
```javascript
try {
throw new Error('my error');
}
catch (e) {
console.error(e.message);
}
// Output:
// my error
```
#### `try...finally`:
```javascript
try {
throw new Error('my error');
}
finally {
console.error('finally');
}
// Output:
// finally
```
*Note:* when you don't `catch` the error, it is in fact not 'catched', even though the `finally` block is executed. That means that the error will continue to the upper `try` block (or main block).
#### `try...catch...finally`:
```javascript
try {
throw new Error('my error');
}
catch (e) {
console.error(e.message);
}
finally {
console.error('finally');
}
// Output:
// my error
// finally
```
Typical usage:
```javascript
try {
openFile(file);
readFile(file)
}
catch (e) {
console.error(e.message);
}
finally {
closeFile(file);
}
```
#### Nested `try...catch`:
You can also:
- Nest a `try-catch` statement inside a `try` block.
- Throw the error upwards.
```javascript
try {
try {
throw new Error('my error');
}
catch (e) {
console.error('inner', e.message);
throw e;
}
finally {
console.log('finally');
}
}
catch (e) {
console.error('outer', e.message);
}
// Output:
// inner my error
// finally
// outer my error
```
#### Types of Error
##### Reference Error
```javascript
var x;
try {
x = y + 1; // y cannot be referenced (used)
}
catch(err) {
console.log(err.name, err.message);
}
// ReferenceError y is not defined
```
##### Syntax Error
```javascript
try {
eval("alert('Hello)"); // Missing ' will produce an error
}
catch(err) {
console.log(err.name,err.message);
}
// SyntaxError Invalid or unexpected token
```
##### Type Error
```javascript
var num = 1;
try {
num.toUpperCase(); // You cannot convert a number to upper case
}
catch(err) {
console.log(err.name, err.message);
}
// TypeError num.toUpperCase is not a function
```
##### URI Error
```javascript
try {
decodeURI("%%%"); // You cannot URI decode these percent signs
}
catch(err) {
console.log(err.name, err.message);
}
// URIError URI malformed
```
#### More Information:
<a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch' target='_blank' rel='nofollow'>MDN</a>
<a href='https://www.w3schools.com/js/js_errors.asp' target='_blank' rel='nofollow'>W3S</a>

View File

@ -0,0 +1,64 @@
---
title: Arrow Functions
---
## Arrow functions
Functions in ES6 have changed a bit. I mean the syntax.
```javascript
// Old Syntax
function oldOne() {
console.log("Hello World..!");
}
// New Syntax
var newOne = () => {
console.log("Hello World..!");
}
```
The new syntax may be confusing a little bit. But I will try to explain the syntax.
There are two parts of the syntax.
1. var newOne = ()
2. => {}
The first part is just declaring a variable and assigning the function (i.e) () to it. It just says the variable is actually a function.
Then the second part is declaring the body part of the function. The arrow part with the curly braces defines the body part.
Another example with parameters:
```javascript
let NewOneWithParameters = (a, b) => {
console.log(a+b); // 30
}
NewOneWithParameters(10, 20);
```
Parentheses are optional when there's only one parameter name:
```javascript
let newOneWithOneParam = a => {
console.log(a);
}
```
An incredible advantage of the arrows function is that you can not rebind an arrow function. It will always be called with the context in which it was defined. Just use a normal function.
```javascript
// Old Syntax
axios.get(url).then(function(response) {
this.data = response.data;
}).bind(this);
// New Syntax
axios.get(url).then(response => {
this.data = response.data;
});
```
I dont think I need to give an explanation for this. It's straightforward.

View File

@ -0,0 +1,55 @@
---
title: Default Parameters
---
## Default Parameters
If you are familiar with other programming languages like Ruby, Python then default parameters isnt new to you.
Default parameters are parameters which are given by default while declaring a function. But its value can be changed when calling the function.
Example
```
let Func = (a, b = 10) => {
return a + b;
}
Func(20); // 20 + 10 = 30
```
In the above example, we are passing only one parameter. The function makes use of the default parameter and executes the function.
Consider another example:
```
Func(20, 50); // 20 + 50 = 70
```
In the above example, the function takes two parameters and the second parameter replaces the default parameter.
Consider another example:
```
let NotWorkingFunction = (a = 10, b) => {
return a + b;
}
NotWorkingFunction(20); // NAN. Not gonna work.
```
When you are calling the function with parameters they get assigned in the order. (i.e) the first value gets assigned to the first parameter and the second value gets assign to the second parameter and so on..
In the above example, the value 20 gets assigned to parameter a and b is not having any value. So we are not getting any output.
But,
```
NotWorkingFunction(20, 30); // 50;
```
Works fine.
However, if you want to use the default first parameter, you can pass `undefined` as the first argument of the function call.
```
NotWorkingFunction(undefined, 30); // 40;
```

View File

@ -0,0 +1,72 @@
---
title: Destructuring Assignment
---
## Destructuring Assignment
Destructuring Assignment syntax is a Javascript expression that makes it possible to unpack values or properties from arrays or objects.
Lets say that you have an array that contains a first name and last name as it's two values, but you want to reassign those values to something more descriptive. You can use Destructuring to accomplish this.
**ES5 Destructuring**
```js
var fullName = ["John", "Smith"];
var firstName = fullName[0];
var lastName = fullName[1];
console.log(firstName, lastName); // John Smith
```
**ES6 Destructuring**
```js
const fullName = ["John", "Smith"];
const [firstName, lastName] = fullName;
console.log(firstName, lastName); // John Smith
```
The examples above show the benefit of using the ES6 Destructuring Assignment.
You can also use Destructuring on objects using a similar syntax
```js
const fullName = { first: "John", last: "Smith"};
const {first, last} = fullName;
console.log(first, last); // John Smith
```
Object Destructuring Assignment is a little bit different because the object must have properties with the names you are assigning. Therefore the code below would not work as intended.
```js
const fullName = { first: "John", last: "Smith"};
const {firstName, lastName} = fullName;
console.log(firstName, lastName); // undefined undefined
```
You can still achieve the desired result using the following syntax.
```js
const obj = {propertyName: value}
const {propertyName: desiredVariableName} = obj
```
Our previous example would be rewritten as follows:
```js
const fullName = { first: "John", last: "Smith"};
const {first: firstName, last: lastName} = fullName;
console.log(firstName, lastName); // John Smith
```
**Array Destructuring with rest**
When destructuring an array, you can unpack and assign the remaining part of it to a variable using the rest pattern:
```js
const [a, ...b] = [1, 2, 3];
console.log(a); // 1
console.log(b); // [2, 3]
```

View File

@ -0,0 +1,96 @@
---
title: for-of loop
---
## for-of Loop
for-of loop can be used to iterate over the things which are not arrays but are iterable like a DOM collection, string, set, arguments or map.
```javascript
const fruits = ['Orange','Apple','Grapes','Banana'];
for (const fruit of fruits)
{
console.log(fruit);
}
```
The above snippet is going to return us the items in the array above.
## for-of loop in knowing index
What if we want to know the index of each item too.In that case we can iterate over fruits.entries() which gives us the ArrayIterator.
```javascript
for (const fruit of fruits.entries())
{
console.log(fruit);
}
```
In the above snippet, fruit is going to be an array with two items. 0th item is going to contain the index and the 1st item would contain the actual fruit name.The output would be like :
```
[0, "Orange"]
[1, "Apple"]
[2, "Grapes"]
[3, "Banana"]
```
We can further destructure fruit like below:
```javascript
for (const [index,fruit] of fruits.entries())
{
console.log(index,fruit);
}
```
## for-of loop in iterating over unknown number of arguments
for-of loop is very helpful in iterating over the unknown number of arguments to a function.
Suppose we want to add the numbers which are passed to a function and the number of arguments is not fixed.
'arguments' is a special keyword in javascript which gives us the Array-ish (not array) type and gives us all of the arguments.
```javascript
function addNumbers()
{
let sum = 0;
for (const num of arguments)
sum+=num;
return sum;
}
addNumbers(1, 2, 3, 4, 5); // 15
```
Here arguments is not a true array still we can iterate over it using for-of loop.
## for-of loop to iterate over string
We can use for-of loop to iterate over string to give us character by character of the string.
```javascript
const name = 'John Doe';
for (const char of name)
console.log(char);
```
which results in following output:
characters 'J' ,'o','h','n',' ','D','o','e'
## for-of loop to iterate over DOM collection
DOM collections are not the true array type. They are usually NodeList for most of the browsers. If we create a number of paragraphs and want to iterate over them to assign some event on each of paragraph, we can make use of for-of loop.
```javascript
const paragraphs = document.querySelectorAll('p');
```
Here paragraphs is a NodeList which can be iterated over using for-of loop.
```javascript
for (const para of paragraphs)
{
console.log(para);
// We can add event listeners to each para here
}
```

View File

@ -0,0 +1,58 @@
---
title: ES6
---
## ES6
The 6th edition of ECMAScript is called ES6.
It is also know as ES2015.
The changes add a lot of syntactic sugar that allow developers to create applications in an object oriented style.
> ES5 example:
```javascript
var User = function () {
function User(name) {
this._name = name;
}
User.prototype.getName = function getName(x) {
return 'Mr./Mrs. ' + this._name;
};
return User;
}();
```
> ES6 example:
```javascript
class User {
constructor(name) {
this._name = name
}
getName() {
return `Mr./Mrs. ${this._name}`
}
}
```
A lot of new syntax features were introduced including:
- classes,
- modules,
- templating,
- for/of loops,
- generator expressions,
- arrow functions,
- collections,
- promises.
Nowadays most of the features are available in all popular browsers. The <a href='https://kangax.github.io/compat-table/es6/' target='_blank' rel='nofollow'>compatibility table</a> contains all information about feature availability of all modern browsers.
Frequently new features arrive that are part of the successor ES7. A common way is to translate modern JavaScript (ES6, ES7 and other experimental proposals) to ES5. This makes sure that also old browsers can execute the code. There are tools like <a href='https://babeljs.io/' target='_blank' rel='nofollow'>Babel</a> that transforms new JavaScript to ES5.
Besides syntactic sugar coming from ECMAScript standards there are features that require a <a href='https://babeljs.io/docs/usage/polyfill' target='_blank' rel='nofollow'>Polyfill</a>. Usually they are necessary because whole class/method implementations were added to the standard.

View File

@ -0,0 +1,52 @@
---
title: Let and Const
---
## Let
let is similar to var but let has scope. let is only accessible in the block level it is defined.
```
if (true) {
let a = 40;
console.log(a); //40
}
console.log(a); // undefined
```
In the above example variable a is defined inside an If statement and so its not accessible outside of the function.
Another example:
```
let a = 50;
let b = 100;
if (true) {
let a = 60;
var c = 10;
console.log(a/c); // 6
console.log(b/c); // 10
}
console.log(c); // 10
console.log(a); // 50
```
## Const
Const is used to assign a constant value to the variable. And the value cannot be changed. It's fixed.
```
const a = 50;
a = 60; // shows error. You cannot change the value of const.
const b = "Constant variable";
b = "Assigning new value"; // shows error.
```
Consider another example.
```
const LANGUAGES = ['Js', 'Ruby', 'Python', 'Go'];
LANGUAGES = "Javascript"; // shows error.
LANGUAGES.push('Java'); // Works fine.
console.log(LANGUAGES); // ['Js', 'Ruby', 'Python', 'Go', 'Java']
```
This may be little confusing.
Consider in this way. Whenever you define a const variable, Javascript references the address of the value to the variable. In our example the variable LANGUAGES actually references to the memory allocated to the array. So you cannot change the variable to reference some other memory location later. Throughout the program it only references to the array.

View File

@ -0,0 +1,24 @@
---
title: Map Function
---
## The Map Function
The `map()` function is used for creating a new array from an existing one, applying a function to each one of the elements of the first array.
The original syntax of the map function is:
```javascript
let new_arr = arr.map(function callback(currentValue, index, array) {
// Do some stuff with currentValue (index and array are optionals)
})
```
### Example (ES6):
```javascript
const myArray_1 = [1, 2, 3, 4];
const myArray_2 = myArray_1.map(el => el * 2);
```
`myArray_2` will contain the elements: `[2, 4, 6, 8]`
`map()` is a method of the `Array` object, so to pass that function to an iterable object it is necessary to make the object an Array.

View File

@ -0,0 +1,64 @@
---
title: New String Functions
---
## New String Functions
Following four functions are added new to strings in ES6.
* startsWith
* endsWith
* includes
* repeat
## startsWith:
This is a case sensitive function which helps us to find if a particular string starts with some substring.
startsWith takes in the second optional argument called position which we can use in case when we want to skip particular number of characters from the beginning of the string before searching.
```javascript
const str ='Rachna';
str.startsWith('Rad') //false
str.startsWith('ra') //false as it is case sensitive
str.startsWith('Ra') //true
str.startsWith('ch',2) //true as we are searching from the second position
str.startsWith('ch',3) //false
```
## endsWith
This is a case sensitive function which helps us to find if a particular string ends with some substring.
endsWith takes in a second optional argument called endPosition which we can use to include the number of characters before searching.
```javascript
const city= 'Delhi';
city.endsWith('Hi'); //false as it is case sensitive
city.endsWith('hi');//true
city.endsWith('l',3);//true - include only first three characters before searching
city.endsWith('l',4);//false
```
## includes
includes function is also a case sensitive function that checks if the searchString is present anywhere in the string.
```javascript
const name='John Doe';
name.includes('do'); //false
name.includes('D'); //true
name.includes('Do'); //true
```
## repeat
repeat allows us to take a string and repeat it a number of times.
```javascript
const str = 'This is repeated';
str.repeat(3); //"This is repeatedThis is repeatedThis is repeated"
```
repeat function can be used to pad a string from Left with a number of spaces.

View File

@ -0,0 +1,25 @@
---
title: Some Function
---
## The Some Function
The `some()` function is used for verifying if at least one element of an array meets a given condition. The function returns `true` if the condition is met by one element, and false if any of the elements met the condition
The original syntax of the some function is:
```javascript
arr.some(function callback(currentValue, index, array) {
// Do some stuff with currentValue (index and array are optionals)
}, [thisArg]);
```
### Example (ES6):
```javascript
const arr = [1, 4, 5, 11];
if (arr.some(el => el % 2 == 0)) {
console.log("There's at least one even number");
}
```
`some()` is a method of the `Array` object, so to pass that function to an iterable object it is necessary to be sure that the object is an Array.

View File

@ -0,0 +1,23 @@
---
title: Spread Operator
---
## Spread Operator
The spread operator (`...`), allows to get the elements of a collection.
One of the most commom uses is for `Node` Objects, when using query selectors in the browser, in order to make them iterable Array Objects:
```javascript
const paragraphs = document.querySelectorAll('p.paragraph');
const arr = [...paragraphs];
```
Another use of the spread operator is for Array concatenation:
```javascript
const arr_1 = [1, 2, 3, 4]
const arr_2 = [5, 6, 7, 8]
const arr_final = [...arr_1, ...arr_2]
// arr_final = [1, 2, 3, 4, 5, 6, 7, 8]
```
### More Information:
- [MDN - Spread Syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)

View File

@ -0,0 +1,67 @@
---
title: Template Literals
---
## Template Literals
## Introduction:
When we want to use variable to make a string, it becomes very painful as we have to use + sign to concatenate and keep track of quotes.
Now with ES6,We can make string using backticks and using placeholders which are indicated with dollar sign and curly braces, like ${expression } .
```javascript
const name='John';
const city='London';
Older Style:
const sentence ='My name is '+ name +'. I live in '+city.
ES6 way:
const sentence = `My name is ${name}. I live in ${city}`;
Here ${name} and ${city}are going to be interpolated by the variable name and city respectively.
```
## MultiLine Strings:
Older style:
When we wanted to span our string into multiple lines, we had to use backslashes.
```javascript
const multipleLineString= "We have \
multiple lines \
here";
```
Now when we want to create a mutiline string, we can make use of template strings.We can surround our string with backticks. This approach is extremely helpful when we want to create some dynamic html markup.
```javascript
const htmlMarkup = `
<html>
<head></head>
<title>Template string</title>
<body>Hello World</body>
</html>`;
```
## Nesting of Template Strings:
We can nest them inside of each other.
```javascript
const cities =[
{name:'Delhi', year: 2010},
{name:'Mumbai', year: 2015},
{name:'Kolkata', year: 2017}];
const markup = `
<ul>
${cities.map(city=>`<li>I lived in ${city.name} in the year ${city.year}</li>`).join('')}
</ul>`;
```
Here the join operator after map function removes the extra commas which are added after each li.
## If statements and Functions
We can also use If statements inside the template strings.
```javascript
const data = {name: 'John', city: 'London', birthyear: 1900};
const markup = `<div>${data.name} lives in ${data.city}. ${data.birthyear ? `<div>He was born in the year ${data.birthyear}</div>`:''}</div>`;
```
In the example above, if birthyear is defined, then div with contents "He was born in the year" is generated otherwise there would be no div created.
We can also call functions inside the template strings.

View File

@ -0,0 +1,72 @@
---
title: Falsy Values
---
## Description
A falsy value is something which evaluates to FALSE, for instance when checking a variable. There are only six falsy values in JavaScript: `undefined`, `null`, `NaN`, `0`, `""` or `''` (empty string), and `false` of course.
## Checking for falsy values on variables
It is possible to check for a falsy value in a variable with a simple conditional:
```javascript
if (!variable) {
// When the variable has a falsy value the condition is true.
}
```
## General Examples
```javascript
var string = ""; // <-- falsy
var filledString = "some string in here"; // <-- truthy
var zero = 0; // <-- falsy
var numberGreaterThanZero; // <-- falsy
var emptyArray = []; // <-- truthy, we'll explore more about this next
var emptyObject = {}; // <-- truthy
```
## Fun With Arrays
```javascript
if ([] == false) // <-- truthy, will run code in if-block
if ([]) // <-- truthy, will also run code in if-block
if ([] == true) // <-- falsy, will NOT run code in if-block
if (![]) // <-- falsy, will also NOT run code in if-block
```
## Caveat
Be aware of the data type when evaluating a value in a Boolean context. If the data type of the value is meant to be a _number_, the truthy/falsy evalution can result in an unexpected outcome:
```javascript
const match = { teamA: 0, teamB: 1 }
if (match.teamA)
// The following won't run due to the falsy evaluation
console.log('Team A: ' + match.teamA);
}
```
An alternative to the use case above is to evaluate the value using `typeof`:
```javascript
const match = { teamA: 0, teamB: 1 }
if (typeof match.teamA === 'number')
console.log('Team A: ' + match.teamA);
}
```
## More Information
- <a>**truthy**</a> | <a href='http://james.padolsey.com/javascript/truthy-falsey/' target='_blank' rel='nofollow'>Blog Post - Truthy & Falsey</a>
- [ Falsy | Glossary | MDN](https://developer.mozilla.org/en-US/docs/Glossary/Falsy)
- [Truthy and Falsy: When All is Not Equal in JavaScript](https://www.sitepoint.com/javascript-truthy-falsy/)

View File

@ -0,0 +1,177 @@
---
title: Form Validation
---
## Form Validation
Form validation normally used to occur at the server, after the client had entered all the necessary data and then pressed the Submit button. If the data
entered by a client was incorrect or was simply missing, the server would have to send all the data back to the client and request that the form be
resubmitted with correct information. This was really a lengthy process which used to put a lot of burden on the server.
JavaScript provides a way to validate form's data on the client's computer before sending it to the web server. Form validation generally performs two
functions:
### Basic Validation
First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and
check for data.
### Data Format Validation
Secondly, the data that is entered must be checked for correct form and value. Your code must include appropriate logic to test correctness of data.
#### Example:
```html
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
</tr>
<tr>
<td align="right">EMail</td>
<td><input type="text" name="EMail" /></td>
</tr>
<tr>
<td align="right">Zip Code</td>
<td><input type="text" name="Zip" /></td>
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="Country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
```
#### Output
Lookout [here](https://liveweave.com/LP9eOP)
### Basic Form Validation
First let us see how to do a basic form validation. In the above form, we are calling validate() to validate data when onsubmit event is occurring. The
following code shows the implementation of this `validate()` function.
```html
<script type="text/javascript">
// Form validation code will come here.
function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" ||
isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 )
{
alert( "Please provide a zip in the format #####." );
document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" )
{
alert( "Please provide your country!" );
return false;
}
return( true );
}
</script>
```
#### Output
Lookout [here](https://liveweave.com/pCPTnP)
### Data Format Validation
Now we will see how we can validate our entered form data before submitting it to the web server.
The following example shows how to validate an entered email address. An email address must contain at least a @ sign and a dot (.). Also, the @ must
not be the first character of the email address, and the last dot must at least be one character after the @ sign.
#### Example:
```html
<script type="text/javascript">
function validateEmail()
{
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
</script>
```
#### Output
Lookout [here](https://liveweave.com/nznVs6)
### HTML5 Form Constraints
Some of commonly used HTML5 constraints for `<input>` are the `type` attribute (e.g. `type="password"`), `maxlength`, `required`and `disabled`. A less
commonly used constraint is the `pattern` attrinute that takes JavaScript regular expression.
### Validation Libraries
Examples of validation libraries include:
* [Validate.js](http://rickharrison.github.com/validate.js/)
* [Validation](http://bassistance.de/jquery-plugins/jquery-plugin-validation/)
* [Valid8](http://unwrongest.com/projects/valid8/)
### More Information
* [Form Data Validation | MDN](https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation)
* [Constraint validation | MDN](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation)
* [Tutorialspoint](https://www.tutorialspoint.com/javascript/javascript_form_validations.htm)

View File

@ -0,0 +1,67 @@
---
title: Function Composition
---
## Function composition
Function composition is the pointwise application of one function to the result of another. Developers do it in a manual manner every day when the nest functions:
```javascript
compose = (fn1, fn2) => value => fn2(fn1(value))
```
But this is hard to read. There is a better way using function composition. Instead of reading them from inside out:
```javascript
add2AndSquare = (n) => square(add2(n))
```
We can use a higher order function to chain them in an ordered way.
```javascript
add2AndSquare = compose( add2, square)
```
A simple implementation of compose would be:
```javascript
compose = (f1, f2) => value => f2( f1(value) );
```
To get even more flexibility we can use the reduceRight function:
```javascript
compose = (...fns) => (initialVal) => fns.reduceRight((val, fn) => fn(val), initialVal);
```
Reading compose from left to right allows a clear chaining of higher order functions. Real world examples are adding authentications, logging and context properties. It's a technique that enables reusability on the highest level. Here are some examples how to use it:
```javascript
// example
const add2 = (n) => n + 2;
const times2 = (n) => n * 2;
const times2add2 = compose(add2, times2);
const add6 = compose(add2, add2, add2);
times2add2(2); // 6
add2tiems2(2); // 8
add6(2); // 8
```
You might think this is advanced functional programming and it's not relevant for frontend programming. But it's also useful in Single Page Applications. For example you can add behavior to a React component by using higher order components:
```javascript
function logProps(InputComponent) {
InputComponent.prototype.componentWillReceiveProps = function(nextProps) {
console.log('Current props: ', this.props);
console.log('Next props: ', nextProps);
};
return InputComponent;
}
// EnhancedComponent will log whenever props are received
const EnhancedComponent = logProps(InputComponent);
```
In conclusion function composition enables reusability of functionality at a very high level. If the functions are structured well it enables developers to created new behavior based upon existing behavior.
It also increases readability of implementations. Instead of nesting functions you can cleary chain functions and create higher order functions with meaningful names.

View File

@ -0,0 +1,72 @@
---
title: Function Invocation
---
## Function Invocation
The code inside a function is executed when the function is invoked. It is common to use the term "call a function" instead of "invoke a function".
Functions must be in scope when they are called. The scope of a function is the function in which it is declared, or the entire program if it is declared at the top level.
```javascript
function myFunction(a, b) {
return a * b;
}
myFunction(10, 2); // Function invocation, will return 20
//optional parameters (es6 only)
//allow to set optional parameters
function myFunction(a, b = 10) {
return a * b;
}
myFunction(1); // Function invocation, will return 10
myFunction(1,5); // Function invocation, will return 5
```
In the example code, a and b are the function's parameters that hold the values 10 and 2, that are the arguments used in the function call.
### Invoking a Function as a Method
In JavaScript, you can define functions as object methods.
The following example creates an object (`myObject`), with two properties (`firstName` and `lastName`), and a method (`fullName`):
```javascript
var myObject = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
myObject.fullName(); // Function invoked as a method, will return "John Doe"
```
### Arrow Functions
In the newest version of Javascript, you can also shorten the syntax by using Arrow Functions.
The following demonstrates two functions. One is written in the standard form, one is written as an arrow function. Keep in mind that arrow functions do not have their own this, arguments, super, or new.target.
```javascript
//regular function
function addStuff(args) {
return args + 2;
}
addStuff(2);
//returns 4
//arrow function
var addStuff = (args) => args + 2;
addStuff(2);
//returns 4
```
This shorthand version of the arrow function has an implicit return so you don't specify a return statement.
### More Information:
- Function documentation: <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions' target='_blank' rel='nofollow'>MDN</a>

View File

@ -0,0 +1,59 @@
---
title: Functions List
---
![Unofficial JS Logo](//discourse-user-assets.s3.amazonaws.com/original/2X/0/0584980f425bfbbe1e14001557ff4f5bab8f61ec.jpg)
JavaScript (JS) is a lightweight, interpreted, programming language with first-class functions. Most well-known as the scripting language for Web pages, many non-browser environments also use it, such as <a href='https://nodejs.org' target='_blank' rel='nofollow'>node.js</a> and <a href='http://couchdb.apache.org/' target='_blank' rel='nofollow'>Apache CouchDB</a>. JS is a prototype-based, multi-paradigm, dynamic scripting language, supporting object-oriented, imperative, and declarative (e.g. functional programming) styles.
JavaScript runs on the client side of the web, which can be used to design / program how the web pages behave on the occurrence of an event. JavaScript is an easy to learn and also powerful scripting language, widely used for controlling web page behaviour.
Checkout <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript' target='_blank' rel='nofollow'>MDN's JavaScript Docs</a>, they are a great asset in learning.
We also have some great articles on our wiki:
- <a href='http://forum.freecodecamp.com/t/advantages-and-disadvantages-of-javascript/14280' target='_blank' rel='nofollow'>Advantages and Disadvantages of JavaScript</a>
- **JavaScript Data Types:**
- <a href='http://forum.freecodecamp.com/t/javascript-boolean/14311' target='_blank' rel='nofollow'>Booleans</a>
- **JavaScript Strings:**
- <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-charat/15932' target='_blank' rel='nofollow'>String.prototype.charAt()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-charcodeat/15933' target='_blank' rel='nofollow'>String.prototype.charCodeAt()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-concat/15935' target='_blank' rel='nofollow'>String.prototype.concat()</a>
- <a href='https://forum.freecodecamp.org/t/javascript-string-prototype-indexof/15936' target='_blank' rel='nofollow'>String.prototype.indexOf()</a>
- <a href='http://forum.freecodecamp.com/t/string-prototype-lastindexof/15939' target='_blank' rel='nofollow'>String.prototype.lastIndexOf()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-match/15941' target='_blank' rel='nofollow'>String.prototype.match()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-replace/15942' target='_blank' rel='nofollow'>String.prototype.replace()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-slice/15943' target='_blank' rel='nofollow'>String.prototype.slice()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-split/15944' target='_blank' rel='nofollow'>String.prototype.split()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-substr/15945' target='_blank' rel='nofollow'>String.prototype.substr()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-substring/15947' target='_blank' rel='nofollow'>String.prototype.substring()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-tolowercase/15948' target='_blank' rel='nofollow'>String.prototype.toLowerCase()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-touppercase/15950' target='_blank' rel='nofollow'>String.prototype.toUpperCase()</a>
- **JavaScript Arrays:**
- <a href='http://forum.freecodecamp.com/t/javascript-array-isarray/14284' target='_blank' rel='nofollow'>Array.isArray()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-concat/14286' target='_blank' rel='nofollow'>Array.prototype.concat()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-every/14287' target='_blank' rel='nofollow'>Array.prototype.every()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-filter/14289' target='_blank' rel='nofollow'>Array.prototype.filter()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-foreach/14290' target='_blank' rel='nofollow'>Array.prototype.forEach()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-indexof/14291' target='_blank' rel='nofollow'>Array.prototype.indexOf()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-join/14292' target='_blank' rel='nofollow'>Array.prototype.join()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-lastindexof/14293' target='_blank' rel='nofollow'>Array.prototype.lastIndexOf()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-map/14294' target='_blank' rel='nofollow'>Array.prototype.map()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-pop/14296' target='_blank' rel='nofollow'>Array.prototype.pop()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-push/14298' target='_blank' rel='nofollow'>Array.prototype.push()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-reduce/14299' target='_blank' rel='nofollow'>Array.prototype.reduce()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-reverse/14300' target='_blank' rel='nofollow'>Array.prototype.reverse()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-shift/14301' target='_blank' rel='nofollow'>Array.prototype.shift()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-slice/14302' target='_blank' rel='nofollow'>Array.prototype.slice()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-some/14304' target='_blank' rel='nofollow'>Array.prototype.some()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-sort/14306' target='_blank' rel='nofollow'>Array.prototype.sort()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-splice/14307' target='_blank' rel='nofollow'>Array.prototype.splice()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-tostring/14308' target='_blank' rel='nofollow'>Array.prototype.toString()</a>
- <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-unshift/14309' target='_blank' rel='nofollow'>Array.prototype.unshift()</a>
- **JavaScript Loops:**
- <a href='http://forum.freecodecamp.com/t/javascript-loops/14681' target='_blank' rel='nofollow'>Loops</a>
- <a href='http://forum.freecodecamp.com/t/javascript-while-loop/14668' target='_blank' rel='nofollow'>While Loop</a>
- <a href='http://forum.freecodecamp.com/t/javascript-do-while-loop/14662' target='_blank' rel='nofollow'>Do While Loop</a>
- <a href='http://forum.freecodecamp.com/t/javascript-for-loop/14666' target='_blank' rel='nofollow'>For Loop</a>
- <a href='http://forum.freecodecamp.com/t/javascript-for-in-loop/14665' target='_blank' rel='nofollow'>For In Loop</a>
- <a href='http://forum.freecodecamp.com/t/javascript-for-of-loop/14671' target='_blank' rel='nofollow'>For Of Loop</a>
Checkout our other articles on JavaScript: <a href='https://www.freecodecamp.com/wiki' target='_blank' rel='nofollow'>https://www.freecodecamp.com/wiki</a>.

View File

@ -0,0 +1,8 @@
---
title: Get Timestamp
---
You can use `Date.now()` to get the current timestamp in milliseconds.
You can easily convert the timestamp to seconds like this: `Math.floor(Date.now() / 1000)`
If your browser does not support `Date.now()`, you can use `new Date().getTime()` to get the timestamp in milliseconds.

View File

@ -0,0 +1,42 @@
---
title: Global Object
---
The global object is an object that is initialized by the JavaScript interpreter before the code is executed. All variables that are declared on the global scope (see: <a href='http://forum.freecodecamp.com/t/scopes-in-javascript/14696' target='_blank' rel='nofollow'>Scopes</a>) are stored in the global object as properties.
In a Node.js environment, the global object can be accessed by the `global` keyword, while in a browser window it can be accessed by the `window` keyword. The `this` keyword also refers to the global object when used in the global scope. Please note that using `this` in the global scope will return `undefined` if `strict mode` is enabled.
For example:
```javascript
// global scope
var foo = "bar";
console.log(global.foo); // bar (in a Node environment)
console.log(window.foo); // bar (in a browser window)
console.log(this.foo); // bar (if strict mode is disabled)
```
The distinction between scopes local to functions and the global scope is important here: the global object only contains the variables that were declared on the global scope, not the local scopes of functions.
The global object also contains the properties `NaN`, `undefined` and `Infinity` and the following functions:
1. `decodeURI()`
2. `decodeURIComponent()`
3. `encodeURI()`
4. `encodeURIComponent()`
5. `escape()`
6. `eval()`
7. `GetObject()`
8. `isFinite()`
9. `isNaN()`
10. `parseFloat()`
11. `parseInt()`
12. `ScriptEngine()`
13. `ScriptEngineBuildVersion()`
14. `ScriptEngineMajorVersion()`
15. `ScriptEngineMinorVersion()`
16. `unescape()`
# References
1. MSDN: <a href='https://msdn.microsoft.com/en-us/library/52f50e9t' target='_blank' rel='nofollow'>Global Object (Javascript)</a>

View File

@ -0,0 +1,64 @@
---
title: Global Variables
---
Global variables are declared outside of a function for accessibility throughout the program, while local variables are stored within a function using `var` for use only within that function's [scope](https://developer.mozilla.org/en-US/docs/Glossary/Scope). If you declare a variable without using `var`, even if it's inside a function, it will still be seen as global:
```javascript
var x = 5; //global
function someThing(y) {
var z = x + y;
console.log(z);
}
function someThing(y) {
x = 5; //still global!
var z = x + y;
console.log(z);
}
function someThing(y) {
var x = 5; //local
var z = x + y;
console.log(z);
}
```
A global variable is also an object of the current scope, such as the browser window:
```javascript
var dog = Fluffy;
console.log(dog); //Fluffy;
var dog = Fluffy;
console.log(window.dog); //Fluffy
```
Its a best practice to minimize global variables. Since the variable can be accessed anywhere in the program, they can cause strange behavior.
References:
* [var -Javascript|MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var)
* [You Don't Know JavaScript: Scopes & Closures](https://github.com/getify/You-Dont-Know-JS/tree/master/scope%20%26%20closures)
Additional Info:
* <a href='http://www.w3.org/wiki/JavaScript_best_practices#Avoid_globals' target='_blank' rel='nofollow'>JavaScript Best Practices: Avoid Globals</a>
* [What's the difference between a global var and a window.variable in javascript?](https://stackoverflow.com/questions/6349232/whats-the-difference-between-a-global-var-and-a-window-variable-in-javascript)
---
The scope of JavaScript variables are either global or local.
Global variables are declared OUTSIDE the function and its value is accessible/changeable throughout the program.
You should ALWAYS use **var** to declare your variables (to make locally) else it will install GLOBALLY
Take care with the global variables because they are risky. Most of the time you should use closures to declare your variables.
Example:
```javascript
(function(){
var myVar = true;
})();
```
#### More Information:
- [JavaScript Best Practices: Avoid Globals](http://www.w3.org/wiki/JavaScript_best_practices#Avoid_globals)
- [Global Variables are bad](http://c2.com/cgi/wiki?GlobalVariablesAreBad)
- [MDN - Global Variables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var)

View File

@ -0,0 +1,108 @@
---
title: Higher Order Functions
---
## Higher Order Functions
A Higher Order Function is any function that returns a function when executed, takes a function as one or more of its arguments, or both. If you have used any of the `Array` methods like `map` or `filter`, or passed a callback function to jQuery's `$.get`, you have already worked with Higher Order Functions.
When you use `Array.map`, you provide a function as its only argument, which it applies to every element contained in the array.
```javascript
const arr = [ 1, 2, 3 ];
const arrDoubled = arr.map(function(num) {
return num * 2;
});
console.log(arrDoubled); // [ 2, 4, 6 ]
```
Higher order functions can also return a function. For example, you can make a function called `multiplyBy` that takes a number and returns a function that multiplies another number you provide by the first number provided. You can use this approach to create a `multiplyByTwo` function to pass to `Array.map`. This will give you the same result you saw above.
```javascript
function multiplyBy(num1) {
return function(num2) {
return num1 * num2;
}
}
const multiplyByTwo = multiplyBy(2);
const arr = [ 1, 2, 3 ];
const arrDoubled = arr.map(multiplyByTwo);
console.log(arrDoubled); // [ 2, 4, 6 ]
```
### Filter Method Example
One amazing example of higher order function is the filter function.
* Filter: It is the function on the array which loops through the array and filter out the value we are looking for.
Below example:
```javascript
const animals = [
{name: 'Fluffykins', species: 'rabbit'},
{name:'Caro', species: 'dog'},
{name: 'Hamilton', species: 'dog'},
{name: 'Harold', species: 'fish'},
{name: 'Ursula', species: 'cat'}
]
```
This example illustrates filtering using imperative programming to simply return a list of species belonging to **dog**.
```javascript
let dogs = [];
for(let i = 0; i < animals.length; i++) {
if(animals[i].species === 'dog')
dogs.push(animals[i])
}
```
Now if we wanted to do the same but this time using filter.
```javascript
const dogs = animals.filter(function(animal) {
return animal.species === 'dog';
})
```
So what is happening here is that filter function takes in an argument, which is another function. A function passed as an argument inside another function is called a callback function. Here `function animal()` is an callback function.
As you can see, the higher-order function has lot less code as compared to the traditional for-loop code. It's not because the syntax is shorter, but because there is lot less logic involved. The only logic used in the filter function in the above example is `return animal.species === 'dog'` which determines which animal goes into the array.
Another reason there is a lot less code, is because this code below
```javascript
for(let i = 0; i < animals.length; i++) {
if(animal[i].species === 'dog') {
dogs.push(animals[i])
}
}
```
is already handled inside the filter function for us so we dont have to worry about it.
The callback function and the filter function just **compose** in one another.
We can decouple the callback function from the filter function like this...
```javascript
const isDog = function(animal) {
return animal.species === 'dog'
}
const dogs = animals.filter(isDog)
```
#### More Information
See the guide on [Closures](https://guide.freecodecamp.org/javascript/closures) for more information on how `multiplyByTwo` keeps a reference to `num1` in the example above.
- [More info about Closures](https://eloquentjavascript.net/05_higher_order.html)
- [Eloquent Javascript](https://eloquentjavascript.net/05_higher_order.html)
- [Medium Article](https://medium.freecodecamp.org/higher-order-functions-in-javascript-d9101f9cf528)

View File

@ -0,0 +1,36 @@
---
title: HTML DOM getElementById Method
---
The `getElementById()` method returns the element that has the id attribute with the specified value. It takes one argument, which is a case-sensitive string of the id for the element you want.
This method is one of the most common methods in the HTML DOM, and is used almost every time you want to manipulate, or get info from, an element in your document. Here's a simple example of the syntax:
**HTML content:**
```html
<div id="demo"></div>
```
**JavaScript content:**
```javascript
document.getElementById("demo"); // Returns the element with id "demo"
```
If you have more than one element with the same value of `id` (bad practice!), `getElementById` will return the first element found:
```html
<div id="demo">First</div>
<div id="demo">Second</div>
```
```javascript
document.getElementById("demo"); // Returns the element with id "demo" containing 'First'
```
#### More Information:
<a href='https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById' target='_blank' rel='nofollow'>document.getElementById()</a>
#### Alternative solutions:
A commonly-used alternative to `document.getElementById` is using a jQuery selector which you read about more [here](https://github.com/freeCodeCamp/guides/tree/master/src/pages/jquery).

View File

@ -0,0 +1,55 @@
---
title: HTML Dom Innerhtml Property
---
## HTML Dom Innerhtml Property
The `innerHTML` prop return the HTML content inside a selected element and also let you define a new HTML content.
***GET ELEMENT CONTENT***
```html
<div id="demo">
<p>Demo</p>
</div>
```
```javascript
var element = document.getElementById("demo");
console.log(element.innerHTML) //logs <p>Demo</p>
```
***SET ELEMENT CONTENT***
```html
<div id="demo"></div>
```
```javascript
var element = document.getElementById("demo");
element.innerHTML = "<div>Demo</div>";
```
The HTML now will be like
```html
<div id="demo">
<div>Demo</div>
</div>
```
***SECURITY CONSIDERATIONS***
The value that's set to `innerHTML` should come from trusted sources, since Javascript will put anything inside that element and it will be run as plain HTML.
Example:
Setting a "`<script>alert();</script>`" value will cause the Javascript "alert()" function to be fired:
```javascript
var element = document.getElementById("demo");
element.innerHTML = "<script>alert();</script>";
```
This type of attack is called [Cross Site Scripting, or XSS for short](https://en.wikipedia.org/wiki/Cross-site_scripting).
This is one of the most common ways of committing an XSS attack. If you want to learn a little bit more and learn to defend against it, [check out this resource](https://xss-game.appspot.com/)

View File

@ -0,0 +1,34 @@
---
title: HTML DOM querySelector()
---
The Document method `querySelector()` returns the `first` Element within the document that matches the specified selector, or group of selectors. If no matches are found,null is returned.
**HTML content:**
```html
<div id="id-example"></div>
<div class="class-example"></div>
<a>element-example</a>
```
**JavaScript content:**
```javascript
document.querySelector("#id-example"); // Returns the element with id "id-example"
document.querySelector(".class-example"); // Returns the element with class "class-example"
document.querySelector("a"); // Returns the "a" element
```
Note `querySelector()` returns the first matching element, to return all the matches, use the querySelectorAll() method instead.
```html
<div id="example">First</div>
<div id="example">Second</div>
```
```javascript
document.querySelector("#example"); // Returns only the element containing 'First'
```
#### More Information:
<a href='https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector' target='_blank' rel='nofollow'>MDN - document.querySelector()</a>

View File

@ -0,0 +1,44 @@
---
title: HTML Dom
---
## HTML Dom
With the HTML DOM, JavaScript can access and change all the elements of an HTML document.
When a web page is loaded, the browser creates a **D**ocument **O**bject **M**odel of the page.
The HTML DOM model is constructed as a tree of Objects:
Each element in the DOM is also called a node.
```html
<html>
<head>
<title> My title </title>
</head>
<body>
<a href="#">My Link</a>
<h1> My header </h1>
</body>
</html>
```
The DOM for the above HTML is as follows:
![DOM tree](https://www.w3schools.com/js/pic_htmltree.gif)
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
* JavaScript can change all the HTML elements in the page
* JavaScript can change all the HTML attributes in the page
* JavaScript can change all the CSS styles in the page
* JavaScript can remove existing HTML elements and attributes
* JavaScript can add new HTML elements and attributes
* JavaScript can react to all existing HTML events in the page
* JavaScript can create new HTML events in the page
#### More Information:
<a href='https://www.w3schools.com/js/js_htmldom.asp' target='_blank' rel='nofollow'>W3C - HTML DOM</a>

View File

@ -0,0 +1,71 @@
---
title: If-Else Statement
---
## Introduction
The `if` statement executes a statement if a specified condition is `true`. If the condition is `false`, another statement can be executed using the `else` statement.
**Note:** The `else` statement is optional.
```javascript
if (condition)
/* do something */
else
/* do something else */
```
Multiple `if...else` statements can be chained to create an `else if` clause. This specifies a new condition to test and can be repeated to test multiple conditions, checking until a true statement is presented to execute.
```javascript
if (condition1)
/* do something */
else if (condition2)
/* do something else */
else if (condition3)
/* do something else */
else
/* final statement */
```
**Note:** If you want to execute more than one statement in the `if`, `else` or `else if` part, curly braces are required around the statements:
```javascript
if (condition) {
/* do */
/* something */
/* with multiple statements */
} else {
/* do something */
/* else */
}
```
<a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else' target='_blank' rel='nofollow'>MDN link</a> | <a href='https://msdn.microsoft.com/en-us/library/85yyde5c.aspx' target='_blank' rel='nofollow'>MSDN link</a>
## Examples
**Using** `if...else`:
```javascript
// If x=5 z=7 and q=42. If x is not 5 then z=19.
if (x == 5) {
z = 7;
q = 42
else
z = 19;
```
**Using** `else if`:
```javascript
if (x < 10)
return "Small number";
else if (x < 50)
return "Medium number";
else if (x < 100)
return "Large number";
else {
flag = 1;
return "Invalid number";
}
```

View File

@ -0,0 +1,63 @@
---
title: Immediately Invoked Functions Expressions(IIFEs)
---
## Function Statement
A function created with a function declaration is a Function object and has all the properties, methods and behavior of Function objects.
Example:
```javascript
function statement(item){
console.log('Function statement example '+ item);
}
```
## Function Expression
A function expression is similar to function statement except that function name can be omitted to create anonymous functions.
Example:
```javascript
var expression = function (item){
console.log('Function expression example '+ item);
}
```
## Immediately Invoked Functions Expressions
A soon as function is created it invokes itself doesn't need to invoke explicitly.
In the below example variable iife will store a string that is returned by the function execution.
```javascript
var iife = function (){
return 'Immediately Invoked Function Expressions(IIFEs) example ';
}();
console.log(iife); // 'Immediately Invoked Function Expressions(IIFEs) example '
```
The statement before IIFE should always end with a ; or it will throw an error.
**Bad example**:
```javascript
var x = 2 //no semicolon, will throw error
(function(y){
return x;
})(x); //Uncaught TypeError: 2 is not a function
```
## Why use Immediately Invoked Functions Expressions?
```javascript
(function(value){
var greet = 'Hello';
console.log(greet+ ' ' + value);
})('IIFEs');
```
In above example when javascript engine execute above code it will create global execution context when it sees code and create function object in memory for IIFE.
And when it reaches on line `46` due to which function is Invoked a new execution context is created on the fly and so greet variable goes into that function execution context not into the global this is what makes it unique.
`This ensures that code inside IIFE does not interfere with other code or be interfered by another code` and so code is safe.
#### More Information
[Immediately-invoked function expression on Wikipedia](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression)
[What does the leading semicolon in JavaScript libraries do?](https://stackoverflow.com/questions/1873983/what-does-the-leading-semicolon-in-javascript-libraries-do)

View File

@ -0,0 +1,19 @@
---
title: Immutable Types
---
> Immutable means unchangeable i.e. you can't change.
Javascript has lots of immutable types e.g. `string` primitive type. Try this in your console.
s = "red";
console.log(s[1]); //→ "e"
s[1] = "x";
console.log(s) //→ "red"
the `s` didn't change! <a>WAT</a>!
## Details
Some string methods like `String.replace` returns a new string.
JavaScript has one complex data type, the Object data type, and it has five simple data types: Number, String, Boolean, Undefined, and Null. These simple (primitive) data types are immutable (cannot be changed), while objects are mutable (can be changed).

View File

@ -0,0 +1,35 @@
---
title: JavaScript
---
## JavaScript
JavaScript is the most widely used scripting language on Earth. And it has the largest library ecosystem of any programming language.
JavaScript is the core language of the web, and the only programming language that can run in all major web browsers.
Notably, JavaScript has no relation to Java. [JavaScript: The World's Most Misunderstood Programming Language](http://www.crockford.com/javascript/javascript.html)
The official name of JavaScript is ECMAScript defined under Standard [ECMA-262](https://www.ecma-international.org/publications/standards/Ecma-262.htm)
If you want to learn more about the JavaScript language, and why it's so widely used, read Quincy Larson's article - [Which programming language should I learn first?](https://medium.freecodecamp.org/what-programming-language-should-i-learn-first-%CA%87d%C4%B1%C9%B9%C9%94s%C9%90%CA%8C%C9%90%C9%BE-%C9%B9%C7%9D%CA%8Dsu%C9%90-19a33b0a467d) -
or watch this [inspiring video from Preethi Kasireddy](https://www.youtube.com/watch?v=VqiEhZYmvKk).
## Standalone JavaScript engines
Mozilla's SpiderMonkey, the first JavaScript engine ever written, currently used in Mozilla Firefox.
V8, Google's JavaScript engine, used in Google Chrome.
Google Apps Script, a cloud-based/server-side interpreter that provides programmatic "macro-like" control of Google Apps services and documents.
Node.js, built on top of V8, a platform which enables server-side applications to be written in JavaScript.
Windows includes JScript, a JavaScript variant in Windows Script Host.
Chakra, a fork of Jscript, is developed by Microsoft and used in their Edge browser.
Mozilla also offers Rhino, an implementation of JavaScript built in Java, typically embedded into Java applications to provide scripting to end users.
WebKit (except for the Chromium project) implements the JavaScriptCore engine.
## JavaScript Frameworks
Most frequently used JavaScript Frameworks are React JS, Angular JS, Create JS, jQuery, nodeJS etc.
For details follow this [link](https://javascriptreport.com/the-ultimate-guide-to-javascript-frameworks/).

View File

@ -0,0 +1,78 @@
---
title: Location Object
---
## Location Object
The "Location" object provides an API (Application Programming Interface) which enables retrieval of a URL, setting of a URL, or access to parts of a URL. It is already implemented for you by default on the Window and Document objects.
Note: There is no public standard that applies to the location object, but all major browsers support it.
### Location Object Properties
| Property | Description |
|----------|---------------------------------------------------------|
| hash | Sets or returns the anchor part (#) of a URL |
| host | Sets or returns the hostname and port number of a URL |
| hostname | Sets or returns the hostname of a URL |
| href | Sets or returns the entire URL |
| origin | Returns the protocol, hostname and port number of a URL |
| pathname | Sets or returns the path name of a URL |
| port | Sets or returns the port number of a URL |
| protocol | Sets or returns the protocol of a URL |
| search | Sets or returns the querystring part of a URL |
### Location Object Methods
| Method | Description |
|-----------|----------------------------------------------|
| assign() | Loads a new document |
| reload() | Reloads the current document |
| replace() | Replaces the current document with a new one |
### Examples
The location objects are accessible by:
```javascript
console.log(window.location);
// > https://guide.freecodecamp.org/javascript/location-object
console.log(document.location);
// > https://guide.freecodecamp.org/javascript/location-object
```
You can also set the Location object of an HTML `<a>` element or an HTML `<area>` element programmatically with JavaScript.
```javascript
var anchor = document.createElement('a');
anchor.url = "https://guide.freecodecamp.org/javascript/location-object";
```
Once you have an object with a URL set (including the window), the Location API allows you to access parts of the URL.
```javascript
console.log(anchor.protocol);
// > https:
console.log(anchor.host);
// > guide.freecodecamp.org (includes port number if applicable. Example: guide.freecodecamp.org:8080)
```
Other properties of "Location" you can access are:
- `anchor.hostname` - *guide.freecodecamp.org*
- `anchor.port` - *8080*
- `anchor.pathname` - */javascript/location-object*
- `anchor.origin` - *https://developer.mozilla.org*
If your URL contains parameters or hashes you can access them like so:
```javascript
// If your URL is https://guide.freecodecamp.org/javascript?param=location#other-properties
console.log(window.location.search);
// > "?param=location"
console.log(document.location.hash);
// > "#other-properties"
```
#### More Information:
<a href='https://www.w3schools.com/jsref/obj_location.asp' target='_blank' rel='nofollow'>W3C - Location Object</a>
[Location](https://developer.mozilla.org/en-US/docs/Web/API/Location)

View File

@ -0,0 +1,62 @@
---
title: Location Reload Method
---
## Location Reload Method
JavaScript `Location.reload()` method provides means to reload the page at current URL.
The syntax is the following:
`object.reload(forcedReload);`, where `forceReload` is an optional parameter.
To simply reload the page, you can input `window.location` as object.
Optional parameters `force reload` is a boolean value, which if set to:
* `True` reloads the page from the server (e.g. does not store the data cached by the browser):
```
window.location.reload(true);
```
* `False` reloads the page using the version of the page cached by the browser.
```
window.location.reload(false);
```
`False` is the default parameter, so if left blank, `object.reload()` reloads the page using the broswer's cached data, i.e. is identical to using the method as `object.reload(false)`.
To create the effect of browser-provided "Refresh"-option, you may want to create HTML-button and do either of the following:
* attach `Location.reload()` to the HTML button-markup, like this:
```
<input type="button" value="Refresh Button" onClick="window.location.reload()">
```
* assign on-click event to the button with the function that uses the method, where the button looks similar to
```
<button type="button" onClick="reloadThePage()">Refresh!</button>
```
```
<script>
function reloadThePage(){
window.location.reload();
}
</script>
```
### Example:
```javascript
// Reload the current resources from the server
window.location.reload(true);
// Reload the current resources from the browser's cache
window.location.reload();
```
This will reload the page at the current URL from the server.
#### More Information:
* [MDN](https://developer.mozilla.org/docs/Web/API/Location/reload)
* [W3 Schools](https://www.w3schools.com/jsref/met_loc_reload.asp)

View File

@ -0,0 +1,91 @@
---
title: Logical Operators
---
# Logical Operators
Logical operators compare Boolean values and return a Boolean response. There are two types of logical operators - Logical AND, and Logical OR. These operators are often written as && for AND, and || for OR.
#### Logical AND ( && )
The AND operator compares two expressions. If the first evaluates as ["truthy"](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), the statement will return the value of the second expression.
If the first evaluates as ["falsy"](https://developer.mozilla.org/en-US/docs/Glossary/Falsy), the statement will return the value of the first expression.
When only involving boolean values (either `true` or `false`), it returns true if only if both expressions are true. If one or both expressions are false, the entire statement will return false.
```js
true && true //returns the second value, true
true && false //returns the second value, false
false && false //returns the first value, false
123 && 'abc' // returns the second value, 'abc'
'abc' && null //returns the second value, null
undefined && 'abc' //returns the first value, undefined
0 && false //returns the first value, 0
```
#### Logical OR ( || )
The OR operator compares two expressions. If the first evaluates as "falsy", the statement will return the value of the second second expression. If the first evaluates as "truthy", the statement will return the value of the first expression.
When only involving boolean values (either `true` or `false`), it returns true if either expression is true. Both expressions can be true, but only one is needed to get true as a result.
```js
true || true //returns the first value, true
true || false //returns the first value, true
false || false //returns the second value, false
123 || 'abc' // returns the first value, 123
'abc' || null //returns the first value, 'abc'
undefined || 'abc' //returns the second value, 'abc'
0 || false //returns the second value, false
```
#### Short-circuit evaluation
&& and || behave as a short-circuit operators.
In case of the logical AND, if the first operand returns false, the second operand is never evaluated and first operand is returned.
In case of the logical OR, if the first value returns true, the second value is never evaluated and the first operand is returned.
#### Logical NOT (!)
The NOT operator does not do any comparison like the AND and OR operators.Moreover it is operated only on 1 operand.
An '!' (exclamation) mark is used for representing the NOT operator.
###### Use of NOT operators
1. conversion of the expression into boolean.
2. returns the inverse of the boolean value obtained in last step.
```js
var spam = 'rinki'; //spam may be equal to any non empty string
var booSpam = !spam;
/*returns false
since when a non-empty string when converted to boolean returns true
inverse of which is evaluated to false.
*/
var spam2 = ''; //spam2 here is equal to empty string
var booSpam2 = !spam2;
/*returns true
since when a empty string when converted to boolean returns false
inverse of which is evaluated to true.
*/
```
#### Tips:
Both logical operators will return the value of the last evaluated expression. For example:
```js
"cat" && "dog" //returns "dog"
"cat" && false //returns false
0 && "cat" //returns 0 (which is a falsy value)
"cat" || "dog" //returns "cat"
"cat" || false //returns "cat"
0 || "cat" //returns "cat"
```
Note that where `&&` returns the first value, `||` returns the second value and vice versa.
#### More information:
* [Javascript Truth Table](https://guide.freecodecamp.org/javascript/truth-table)
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Logical_Operators)

View File

@ -0,0 +1,46 @@
---
title: Break Statement
---
## Introduction
The **break** statement terminates the current loop, `switch` or `label` statement and transfers program control to the statement following the terminated statement.
break;
If the **break** statement is used in a labeled statement, the syntax is as follows:
break labelName;
## Examples
The following function has a **break** statement that terminates the `while` loop when **i** is 3, and then returns the value **3 * x**.
function testBreak(x) {
var i = 0;
while (i < 6) {
if (i == 3) {
break;
}
i += 1;
}
return i * x;
}
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/C7VM/0' target='_blank' rel='nofollow'>Run Code</a>
In the following example, the counter is set up to count from 1 to 99; however, the **break** statement terminates the loop after 14 counts.
for (var i = 1; i < 100; i++) {
if (i == 15) {
break;
}
}
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/C7VO/0' target='_blank' rel='nofollow'>Run Code</a>
## Other resources:
<a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break' target='_blank' rel='nofollow'>MDN link</a> | <a href='https://msdn.microsoft.com/en-us/library/3fhdxafb.aspx' target='_blank' rel='nofollow'>MSDN link</a>

View File

@ -0,0 +1,53 @@
---
title: Continue Statement
---
## Introduction
The **continue** statement terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.
continue;
If the **continue** statement is used in a labeled statement, the syntax is as follows:
continue labelName;
In contrast to the **break** statement, **continue** does not terminate the execution of the loop entirely; instead:
- In a `while` loop, it jumps back to the condition.
- In a `for` loop, it jumps to the update expression.
## Examples
The following example shows a `while` loop that has a **continue** statement that executes when the value of **i** is 3\. Thus, **n** takes on the values 1, 3, 7, and 12.
var i = 0;
var n = 0;
while (i < 5) {
i++;
if (i === 3) {
continue;
}
n += i;
console.log (n);
}
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/C7hx/0' target='_blank' rel='nofollow'>Run Code</a>
In the following example, a loop iterates from 1 through 9\. The statements between **continue** and the end of the `for` body are skipped because of the use of the **continue** statement together with the expression `(i < 5)`.
for (var i = 1; i < 10; i++) {
if (i < 5) {
continue;
}
console.log (i);
}
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/C7hs/0' target='_blank' rel='nofollow'>Run Code</a>
## Other Resources
* [MDN link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue)
* [MSDN link](https://msdn.microsoft.com/en-us/library/8de3fkc8.aspx)

View File

@ -0,0 +1,35 @@
---
title: Do...While Loop
---
The `do...while` loop is closely related to <a href='http://forum.freecodecamp.com/t/javascript-while-loop/14668' target='_blank' rel='nofollow'>`while`</a> loop. In the do while loop, the condition is checked at the end of the loop.
Here is the **syntax** for `do...while` loop:
## Syntax:
do {
*Statement(s);*
} while (*condition*);
**statement(s):** A statement that is executed **at least once** before the condition or Boolean expression is evaluated and is re-executed each time the condition evaluates to true.
**condition:** Here, a condition is a <a>Boolean expression</a>. If Boolean expression evaluates to true, the statement is executed again. When Boolean expression evaluates to false, the loops ends.
## Example:
var i = 0;
do {
i = i + 1;
console.log(i);
} while (i < 5);
Output:
1
2
3
4
5
source: <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while' target='_blank' rel='nofollow'>**do...while**</a>

View File

@ -0,0 +1,71 @@
---
title: For...In Loop
---
The `for...in` statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
for (variable in object) {
...
}
| Required/Optional | Parameter | Description |
|-------------------|-----------|----------------------------------------------------------------------|
| Required | Variable | A different property name is assigned to variable on each iteration. |
| Optional | Object | Object whose enumerable properties are iterated. |
## Examples
// Initialize object.
a = { "a": "Athens", "b": "Belgrade", "c": "Cairo" }
// Iterate over the properties.
var s = ""
for (var key in a) {
s += key + ": " + a[key];
s += "<br />";
}
document.write (s);
// Output:
// a: Athens
// b: Belgrade
// c: Cairo
// Initialize the array.
var arr = new Array("zero", "one", "two");
// Add a few expando properties to the array.
arr["orange"] = "fruit";
arr["carrot"] = "vegetable";
// Iterate over the properties and elements.
var s = "";
for (var key in arr) {
s += key + ": " + arr[key];
s += "<br />";
}
document.write (s);
// Output:
// 0: zero
// 1: one
// 2: two
// orange: fruit
// carrot: vegetable
// Efficient way of getting an object's keys using an expression within the for-in loop's conditions
var myObj = {a: 1, b: 2, c:3}, myKeys = [], i=0;
for (myKeys[i++] in myObj);
document.write(myKeys);
//Output:
// a
// b
// c
# Ohter Resources:
* [MDN link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in)
* [MSDN link](https://msdn.microsoft.com/library/55wb2d34.aspx)

View File

@ -0,0 +1,84 @@
---
title: For Loop
---
### Syntax
```javascript
for ([initialization]); [condition]; [final-expression]) {
// statement
}
```
The javascript `for` statement consists of three expressions and a statement:
## Description
* initialization - Run before the first execution on the loop. This expression is commonly used to create counters. Variables created here are scoped to the loop. Once the loop has finished it's execution they are destroyed.
* condition - Expression that is checked prior to the execution of every iteration. If omitted, this expression evaluates to true. If it evaluates to true, the loop's statement is executed. If it evaluates to false, the loop stops.
* final-expression - Expression that is run after every iteration. Usually used to increment a counter. But it can be used to decrement a counter too.
* statement - Code to be repeated in the loop
any of these three expressions or the statement can be omitted. For loops are commonly used to count a certain number of iterations to repeat a statement. Use a `break` statement to exit the loop before the condition expression evaluates to false.
## Common Pitfalls
**Exceeding the bounds of an array**
When indexing over an array many times it is easy to exceed the bounds of the array (ex. try to reference the 4th element of a 3 element array).
```javascript
// This will cause an error.
// The bounds of the array will be exceeded.
var arr = [ 1, 2, 3 ];
for (var i = 0; i <= arr.length; i++) {
console.log(arr[i]);
}
output:
1
2
3
undefined
```
There are two ways to fix this code. Set the condition to either `i < arr.length` or `i <= arr.length - 1`
### Examples
Iterate through integers from 0-8
```javascript
for (var i = 0; i < 9; i++) {
console.log(i);
}
output:
0
1
2
3
4
5
6
7
8
```
Break out of a loop before condition expression is false
```javascript
for (var elephant = 1; elephant < 10; elephant+=2) {
if (elephant === 7) {
break;
}
console.info('elephant is ' + elephant);
}
output:
elephant is 1
elephant is 3
elephant is 5
```
### Other Resources
* [MDN - for statements](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for)

View File

@ -0,0 +1,86 @@
---
title: For...Of Loop
---
The `for...of` statement creates a loop iterating over iterable objects (including Array, Map, Set, Arguments object and so on), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
```javascript
for (variable of object) {
statement
}
```
| | Description |
|----------|-------------------------------------|
| variable | On each iteration a value of a different property is assigned to variable. |
| object | Object whose enumerable properties are iterated. |
## Examples
### Array
```javascript
let arr = [ "fred", "tom", "bob" ];
for (let i of arr) {
console.log(i);
}
// Output:
// fred
// tom
// bob
```
### Map
```javascript
var m = new Map();
m.set(1, "black");
m.set(2, "red");
for (var n of m) {
console.log(n);
}
// Output:
// 1,black
// 2,red
```
### Set
```javascript
var s = new Set();
s.add(1);
s.add("red");
for (var n of s) {
console.log(n);
}
// Output:
// 1
// red
```
### Arguments object
```javascript
// your browser must support for..of loop
// and let-scoped variables in for loops
function displayArgumentsObject() {
for (let n of arguments) {
console.log(n);
}
}
displayArgumentsObject(1, 'red');
// Output:
// 1
// red
```
# Other Resources:
* [MDN link](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of)
* [MSDN link](https://msdn.microsoft.com/library/dn858238%28v=vs.94%29.aspx?f=255&MSPPError=-2147217396)
* [arguments @@iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/@@iterator)

View File

@ -0,0 +1,14 @@
---
title: Loops
---
Loops are used in JavaScript to perform repeated tasks based on a condition. Conditions typically return `true` or `false` when analysed. A loop will continue running until the defined condition returns `false`.
There are three common types of loops:
* <a href='http://forum.freecodecamp.com/t/javascript-for-loop/14666' target='_blank' rel='nofollow'>for</a>
* <a href='http://forum.freecodecamp.com/t/javascript-while-loop/14668' target='_blank' rel='nofollow'>while</a>
* <a href='http://forum.freecodecamp.com/t/javascript-for-loop/14662' target='_blank' rel='nofollow'>do while</a>
You can type `js for`, `js while` or `js do while` to get more info on any of these.
> Links: <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for' target='_blank' rel='nofollow'>MDN **for loop**</a>

View File

@ -0,0 +1,79 @@
---
title: Labeled Statement
---
## Labeled Statement
The **Labeled Statement** is used with the `break` and `continue` statements and serves to identify the statement to which the `break` and `continue` statements apply.
### Syntax
``` javascript
labelname:
statements
```
### Usage
Without the use of a `labeled` statement the `break` statement can only break out of a loop or a `switch` statement. Using a `labeled` statement allows `break` to jump out of any code block.
#### Example
``` javascript
foo: {
console.log("This prints:");
break foo;
console.log("This will never print.");
}
console.log("Because execution jumps to here!")
/* output
This prints:
Because execution jumps to here! */
```
When used with a `continue` statement the `labeled` statement allows you to skip a loop iteration, the advantage comes from being able to jump out from an inner loop to an outer one when you have nested loop statements. Without the use of a `labeled` statement you could only jump out of the existing loop iteration to the `next iteration of the same loop.`
#### Example
``` javascript
// without labeled statement, when j==i inner loop jumps to next iteration
function test() {
for (var i = 0; i < 3; i++) {
console.log("i=" + i);
for (var j = 0; j < 3; j++) {
if (j === i) {
continue;
}
console.log("j=" + j);
}
}
}
/* output
i=0 (note j=0 is missing)
j=1
j=2
i=1
j=0 (note j=1 is missing)
j=2
i=2
j=0
j=1 (note j=2 is missing)
*/
// using a labeled statement we can jump to the outer (i) loop instead
function test() {
outer: for (var i = 0; i < 3; i++) {
console.log("i=" + i);
for (var j = 0; j < 3; j++) {
if (j === i) {
continue outer;
}
console.log("j=" + j);
}
}
}
/*
i=0 (j only logged when less than i)
i=1
j=0
i=2
j=0
j=1
*/
```
### More Information:
<a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label' target='_blank' rel='nofollow'>MDN</a>

View File

@ -0,0 +1,42 @@
---
title: While Loop
---
The while loop starts by evaluating the condition. If the condition is true, the statement(s) is/are executed. If the condition is false, the statement(s) is/are not executed. After that, while loop ends.
Here is the **syntax** for while loop:
## Syntax:
while (condition)
{
statement(s);
}
_statement(s):_ A statement that is executed as long as the condition evaluates to true.
_condition:_ Here, condition is a Boolean expression which is evaluated before each pass through the loop. If this condition evaluates to true, statement(s) is/are executed. When condition evaluates to false, execution continues with the statement after the while loop.
## Example:
var i = 1;
while (i < 10)
{
console.log(i);
i++; // i=i+1 same thing
}
Output:
1
2
3
4
5
6
7
8
9
*Source: [While Loop - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while)*

View File

@ -0,0 +1,24 @@
---
title: Manipulate JavaScript Objects
---
There are a couple ways to manipulate object properties, dot notation and bracket notation.
Adding properties to objects with dot notation:
myObject.myProperty = "myValue";
Adding properties to objects using bracket notation:
```javascript
myObject['myProperty'] = "myValue";
```
Using bracket notation, we can utilize variables as property names:
```javascript
var dynamicProperty = "myProperty";
myObject[dynamicProperty] = "myValue";
```
We can also delete them like this:
delete(myObject.myProperty);

View File

@ -0,0 +1,69 @@
---
title: Manipulating Cookies
---
## Manipulating Cookies
Getting or setting cookies is a straightforward operation that can be achived by accessing the cookie property on the browser's document object.
You find an amazing and informative recipe website to cook a foreign meal for your guests but it's in foreign language, luckily you are able to change the language on the site website using a selection dropdown. A couple of days later you visit the same site again to make a dish for your mother, but now you see the website in your native language by default.
*The website remembers language you selected on your last visit and stores it in form of a **cookie**. Now it automatically selected your preferred language by reading that cookie.*
`userLanguage:french`
Cookies are used to store data in form of `name:value` pair on the client side part. It lets a website store user specific information on the browser for later use. The stored information could be `sessionID`, `userCountry`, `visitorLanguage` etc.
Another way to store the data on the client side is `localstorage`.
### Set Cookie
A cookie can be set using the syntax below but a library, like the one mentioned at the end, is highly recommended to make development easier for everyone. While setting the cookie, you can set the expiry for it as well. If skipped, cookie is erased when browser is closed.
**Keep in mind a cookie set by a particular domain can only be read by that domain & it's subdomains only.**
```javascript
// Using vanilla javascript
document.cookie = 'userLanguage=french; expires=Sun, 2 Dec 2017 23:56:11 UTC; path=/';
//Using JS cookie library
Cookies.set('userLanguage', 'french', { expires: 7, path: '/' });
```
*Cookie expires in 7 days*
### Get Cookie
```javascript
// Using vanilla javascript
console.log(document.cookie)
// => "_ga=GA1.2.1266762736.1473341790; userLanguage=french"
// Using JS cookie library
Cookies.get('userLanguage');
// => "french"
```
### Delete Cookie
In order to delete a cookie set the expires date to something in the past.
```javascript
// Using vanilla javascript
document.cookie = 'userLanguage; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/';
//Using JS cookie library
Cookies.remove('userLanguage');
```
*If you find yourself playing with cookies a lot in your project, please use a library like this [JS Cookie](https://github.com/js-cookie/js-cookie) and save yourself a ton of time.*
#### More Information:
- [Cookie explained](https://www.quirksmode.org/js/cookies.html)
- [MDN Cookie Guide](https://developer.mozilla.org/en-US/docs/Web/API/document/cookie)
- [Udacity Cookie Video](https://www.youtube.com/watch?v=xdH9zsW1CK0)
- [HTTP cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies)

View File

@ -0,0 +1,10 @@
---
title: Multiply Two Numbers with JavaScript
---
JavaScript uses use the `*` symbol for multiplication.
var product = 8 * 10;
the 'product' would have the value '80' after this line.
When making calculations it is possible to use parentheses to prioritise which numbers should be multiplied together.

View File

@ -0,0 +1,22 @@
---
title: Naming Convention for JavaScript
---
Here you will get an overview of the different code cases that are widely used.
## camelCase
In programming, camelCase formatting for variable names looks like this:
var camelCase = "lower-case first word, capitalize each subsequent word";
## PascalCase
PascalCase (or CamelCase) is a variant of camelCase. It differs from camelCase by capitalizing every word, *including* the first word:
var PascalCase = "upper-case every word";
## snake_case
Another popular case called snake_case separates each word with underscores in this manner:
var snake_case = "lower-case everything, but separate words with underscores";

View File

@ -0,0 +1,78 @@
---
title: Numbers
---
## Numbers
The implementation of JavaScript's `number`s is based on the `IEEE 754` standard, often called "floating-point."
<a href='https://en.wikipedia.org/wiki/IEEE_754' target='_blank' rel='nofollow'>IEEE 754 Wikipedia Link</a>
<br>
<a href='http://bartaz.github.io/ieee754-visualization/' target='_blank' rel='nofollow'>IEEE 754 Double Precision Floating Point Visualization</a>
Number literals are expressed generally as `base-10` decimal literals.
```javascript
var foo = 47;
var bar = 47.9;
```
The leading portion of a decimal value, if `0`, is optional:
```javascript
var same = 0.47;
var stillSame = .47;
```
Similarly, the trailing portion (the fractional) of a decimal value after the `.`, if `0`, is optional:
```javascript
var a = 47.0;
var b = 47.;
```
By default, most numbers will be outputted as `base-10` decimals, with trailing fractional `0`s removed. So:
```javascript
var foo = 47.300;
var bar = 47.0;
foo; // 47.3
bar; // 47
```
Very large or very small `numbers` can be written as:
```javascript
var foo = 47e8; // 4700000000
var baz = 47e-8; // 00.00000047
```
`toExponential` method can be used to convert a `number` into its `exponential notation`.
```javascript
var foo = 47e8;
foo; // 4700000000
foo.toExponential() //"47e8"
```
Numbers have access to methods that are built into `Number.prototype`.
For Example:
`toFixed()` method formats a number with a specific number of digits to the right of the decimal.
```javascript
var foo = 47.69;
foo.toFixed(0); // "48"
foo.toFixed(1); // "47.7"
foo.toFixed(2); // "47.69"
```
>Type `Number.prototype` in your browser and see other available methods yourself.
#### More Information:
1. <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type' target='_blank' rel='nofollow'>MDN</a>
2. <a href='https://www.w3schools.com/js/js_numbers.asp' target='_blank' rel='nofollow'>JavaScript Numbers</a>
#### References
1. <a href='https://github.com/getify/You-Dont-Know-JS/tree/master/types%20%26%20grammar' target='_blank' rel='nofollow'>Types & grammar</a> by Kyle Simpson.
2. <a href='https://www.ecma-international.org/ecma-262/5.1/#sec-4.3.20' target='_blank' rel='nofollow'>ECMAScript Language Specification: 4.3.20</a>
3. <a href='https://www.ecma-international.org/ecma-262/5.1/#sec-15.7' target='_blank' rel='nofollow'>ECMAScript Language Specification: 15.7 Number Objects</a>

View File

@ -0,0 +1,137 @@
---
title: Functional
---
```javascript
var fun = function(a, b) {
var funInstance = {};
funInstance.a = a;
funInstance.b = b;
funInstance.method1 = function() {
// method code here
}
funInstance.method2 = function() {
// method code here
}
funInstance.method3 = function() {
// method code here
}
return funInstance;
}
var myFun = fun(1, 2);
myFun.method1();
```
## How do I recognize it?
Functional object instantiation creates a class instance with a function, like the other options do. The difference is that all associated methods are also defined in the constructor function.
## Why would I use it?
Since a new set of methods are created for each instance of the object and could take up a considerate amount of memory, functional instantiation is good for when you know that you arent going to be working with a lot of instances. It is also good for having your code easily understood by new and seasoned JavaScript coders alike, since the instantiation is completely self contained and it is easy to see the relationships between the methods and the object instances.
## What are the drawbacks?
The down side with Functional Instantiation is that if you were to make any changes to your code (such as adding more methods), any instances of the object that were created before these changes were made would not get updated. You could end up with two instances containing different method information.
---
title: Functional-Shared
---
```javascript
var fun = function(a, b) {
var funInstance = {};
funInstance.a = a;
funInstance.b = b;
extend(funInstance, funMethods);
return funInstance;
}
var extend = function(to, from) {
for (var key in from) {
to[key] = from[key];
}
}
var funMethods = {};
funMethods.method1 = function() {
// method code here
}
funMethods.method2 = function() {
// method code here
}
funMethods.method3 = function() {
// method code here
}
var myFun = fun(1, 2);
myFun.method1();
```
## How do I recognize it?
The main difference between Functional and Functional-Shared, is that in Functional-Shared we share our methods. Rather than declare methods in our Instantiation function, we have a separate object holding all of our methods. In order to use the methods, we extend them into each instance of the object that is being created.
## Why would I use it?
Functional-Shared allows for us to use references to methods, rather than declaring and storing our methods for each instance of our object, saving us space.
## What are the drawbacks?
The downside is that since the methods are being referenced via pointers to the methods object, if we were to update the methods object in any way, the instances of the object that were created before the changes would not be updated. You could end up with two instances of the object referencing two different versions of the methods.
---
title: Prototypal
---
```javascript
var fun = function(a, b) {
var funInstance = Object.create(funMethods);
funInstance.a = a;
funInstance.b = b;
return funInstance;
}
var funMethods = {};
funMethods.method1 = function() {
// method code here
}
funMethods.method2 = function() {
// method code here
}
funMethods.method3 = function() {
// method code here
}
var myFun = fun(1, 2);
myFun.method1();
```
## How do I recognize it?
Prototypal is similar to Functional-Shared in that they both use a separate methods object to hold all of the methods that will be shared between the instances of the object we are creating. The difference is that we can use the prototype chain. We can create the object using Object.create(prototype) in order to attach the methods to our object instance. The object that is holding our shared methods is considered the prototype.
## Why would I use it?
If you make changes to your prototype after creating an object instance, that instance will be updated. You wont end up with two instances with the same prototype that have different methods.
## What are the drawbacks?
The drawbacks of using this method is that it requires extra steps and extra code. We have to not only create and return our object like before, but we also have to decorate it.
---
title: Pseudoclassical
---
```javascript
var Fun = function(a, b) {
// this = Object.create(Fun.prototype);
this.a = a;
this.b = b;
// return this;
}
Fun.prototype.method1 = function() {
// method code here
}
Fun.prototype.method2 = function() {
// method code here
}
Fun.prototype.method3 = function() {
// method code here
}
var myFun = new Fun(1, 2);
myFun.method1();
```
## How do I recognize it?
Pseudoclassical Instantiation is by far contains the least amount of code. Rather than creating a new object and returning it, the new keyword does that for us. Under the hood, when you use the new keyword to instantiate an object, you create a new object using this = Object.create(Object.prototype), where this refers to the prototype that is named after the new keyword. When we are defining our methods, we use the prototype keyword.
## Why would I use it?
Pseudoclassical is said to be the fastest instantiation pattern, which is helpful if you are creating tens of thousands of instances. It is also the most optimized since it utilizes Javascript functionality.
## What are the drawbacks?
The downside of Pseudoclassical Instantiation is that it requires a bit more knowledge about what JavaScript is doing under the hood, particularly with the this keyword. This makes this type of object instantiation a bit more complex to understand, especially if someone else is reading your code

View File

@ -0,0 +1,77 @@
---
title: Object Instantiation
---
## Object Instantiation
In Javascript and most other languages, an object contains a series of properties, which are a key, value pair. There are multiple options available to you when you need to construct an object.
### Initialize an object variable
You can create an object with pre-defined properties like so:
```javascript
let myObject = {
name: "Dave",
age: 33
}
```
### Creating an empty object
This creates an empty object inside our myObject variable:
```javascript
let myObject = new Object();
```
When you wish to add properties to your object, you simply use either dot notation or bracket notation with the property name of your choice:
```javascript
myObject.name = "Johnny Mnemonic"
myObject["age"] = 55
```
### Using a constructor function
You can define a constructor function that you can use to create your objects:
```javascript
function Kitten(name, cute, color) {
this.name = name,
this.cute = cute,
this.color = color
}
```
You can define a variable containing an instantiation of this object by calling the constructor function:
```javascript
let myKitten = new Kitten("Nibbles", true, "white")
```
### Object.create()
The Object.create() method (first defined in ECMAScript 5.1) allows you to create objects. it allows you to choose the prototype object for your new object without needing to define a constructor function beforehand.
```javascript
// Our pre-defined object
let kitten = {
name: "Fluff",
cute: true,
color: "gray"
}
// Create a new object using Object.create(). kitten is used as the prototype
let newKitten = Object.create(kitten)
console.log(newKitten.name) // Will output "Fluff"
```
#### More Information
<a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects' target='_blank' rel='nofollow'>MDN article on working with objects</a>

View File

@ -0,0 +1,62 @@
---
title: Onclick Event
---
## Onclick Event
The `onclick` event in JavaScript lets you as a programmer execute a function when an element is clicked.
### Example
```javascript
<button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
alert('Button was clicked!');
}
</script>
```
In the simple example above, when a user clicks on the button they will see an alert in their browser showing `Button was clicked!`.
### Adding `onclick` dynamically
The `onclick` event can also be programmatically added to any element using the following code in the following example:
```javascript
<p id="foo">click on this element.</p>
<script>
var p = document.getElementById("foo"); // Find the paragraph element in the page
p.onclick = showAlert; // Add onclick function to element
function showAlert(event) {
alert("onclick Event triggered!");
}
</script>
```
### Note ###
It's important to note that using onclick we can add just one listener function. If you want to add more, just use addEventListener(), which is the preferred way for adding events listener.
In the above example, when a user clicks on the `paragraph` element in the `html`, they will see an alert showing `onclick Event triggered`.
### Preventing default action
However if we attach `onclick` to links (HTML's `a` tag) we might want prevent default action to occur:
```javascript
<a href="https://guide.freecodecamp.org" onclick="myAlert()">Guides</a>
<script>
function myAlert(event) {
event.preventDefault();
alert("Link was clicked but page was not open");
}
</script>
```
In the above example we prevented default behavior of `a` element (opening link) using `event.preventDefault()` inside our `onclick` callback function.
<a href='https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onclick' target='_blank' rel='nofollow'>MDN</a>
#### Other Resources
<a href='https://api.jquery.com/on/' target='_blank' rel='nofollow'>jQuery .on() Event Handler Attachment</a>

View File

@ -0,0 +1,28 @@
---
title: Onload Event
---
## Onload Event
The `onload` event is used to execute a JavaScript function immediately after a page has been loaded.
### Example:
```javascript
<body onload="myFunction()">
<script>
function myFunction() {
alert('Page finished loading');
}
</script>
```
In the above example, as soon as the web page has loaded, the `myFunction` function will be called, showing the `Page finished loading` alert to the user.
the `onload` event is most often used within the `<body>` element to execute the script. If it is attached to the `<body>`, the script will run once the web page has completely loaded all content (images, script files, CSS files, etc.).
#### More Information:
<a href='https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload' target='_blank' rel='nofollow'>MDN</a>
#### Other Resources
<a href='https://api.jquery.com/on/' target='_blank' rel='nofollow'>jQuery .on() Event Handler Attachment</a>
<a href='https://stackoverflow.com/questions/588040/window-onload-vs-document-onload' target='_blank' rel='nofollow'>Stack Overflow: window.onload vs. document.onload</a>

View File

@ -0,0 +1,102 @@
---
title: Output
---
## Output
There are 4 most common ways you will be outputting your data through console. These will be used the most part of your development process.
#### `console.log`
It is the most common and used way to output the data. It's a common practice to insert a couple of these between statements to uderstand how the data is flowing and processed. Also, you can use `debugger` or breakpoints in devtools to do the same without polluting your code.
```javascript
var numbers = [ 1, 2, 3, 4, 5, 6, 7];
numbers.forEach(function(number){
console.log(number + ' is divisible by 2', number%2 == 0);
});
```
#### `console.warn`
As you guessed by the name this is used for showing warnings, and it's typical yellow color differentiates it from error red & `console.log`.
```javascript
function isAdult(age){
if(Number(age) < 18){
console.warn('You are not an adult');
return false;
}
return true;
}
```
#### `console.error`
As you can guess, this is used when throwing an exception or in error in code. Gives you the red error message to grab attention fast.
#### `console.table`
Suppose you got a list of items or movies in a json object and you want to check that out in table format, then `console.table` is your best bet. It automatically detects rows and column headers from data.
*Try to run the code below in your console*
```javascript
var data = {
"colors": [
{
"color": "black",
"category": "hue",
"type": "primary",
"rgba": [255,255,255,1],
"hex": "#000"
},
{
"color": "white",
"category": "value",
"rgba": [0,0,0,1],
"hex": "#FFF"
},
{
"color": "red",
"category": "hue",
"type": "primary",
"rgba": [255,0,0,1],
"hex": "#FF0"
},
{
"color": "blue",
"category": "hue",
"type": "primary",
"rgba": [0,0,255,1],
"hex": "#00F"
},
{
"color": "yellow",
"category": "hue",
"type": "primary",
"rgba": [255,255,0,1],
"hex": "#FF0"
},
{
"color": "green",
"category": "hue",
"type": "secondary",
"rgba": [0,255,0,1],
"hex": "#0F0"
},
]
}
console.table(data.colors);
```
Also, you can control & filter the type of output you wish to see in console.
1. All
2. Verbose
3. Warning
4. Errors
#### More Information:
- <a href='https://developers.google.com/web/tools/chrome-devtools/console/console-reference' target='_blank' rel='nofollow'>Complete reference of console object by Google</a>
- <a href='https://developer.mozilla.org/en-US/docs/Web/API/Console' target='_blank' rel='nofollow'>Console MDN</a>

View File

@ -0,0 +1,63 @@
---
title: Popup Boxes
---
## Popup Boxes
Popup boxes (or dialog boxes) are modal windows used to notify or warn the user, or to get input from the user.
Popup boxes prevent the user from accessing other aspects of a program until the popup is closed, so they should not be overused.
There are three different kinds of popup methods used in JavaScript: <a href='https://developer.mozilla.org/en-US/docs/Web/API/Window/alert' target='_blank' rel='nofollow'>window.alert()</a>, <a href='https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm' target='_blank' rel='nofollow'>window.confirm()</a> and <a href='https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt' target='_blank' rel='nofollow'>window.prompt()</a>.
### Alert
The <a href='https://developer.mozilla.org/en-US/docs/Web/API/Window/alert' target='_blank' rel='nofollow'>alert method</a> displays messages that don't require the user to enter a response. Once this function is called, an alert dialog box will appear with the specified (optional) message. Users will be required to confirm the message before the alert goes away.
### Example:
`window.alert("Hello world");`
![MDN Alert Example](https://mdn.mozillademos.org/files/130/AlertHelloWorld.png)
### Confirm
The <a href='https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm' target='_blank' rel='nofollow'>confirm method</a> is similar to `window.alert()`, but also displays a cancel button in the popup. The buttons return boolean values: true for OK and false for Cancel.
### Example:
```javascript
var result = window.confirm('Do you really want to leave?');
if (result === true) {
window.alert('Okay, if you're sure.');
} else {
window.alert('You seem uncertain.');
}
```
![MDN Confirm Example](https://mdn.mozillademos.org/files/7163/firefoxcomfirmdialog_zpsf00ec381.png)
### Prompt
The <a href='https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt' target='_blank' rel='nofollow'>prompt method</a> is typically used to get text input from the user. This function can take two arguments, both of which are optional: a message to display to the user and a default value to display in the text field.
### Example:
`var age = prompt('How old are you?', '100');`
![MDN Prompt Example](https://mdn.mozillademos.org/files/11303/prompt.png)
### Other Design Options:
If you are unhappy with the default JavaScript popups, you can substitute in various UI libraries. For example, SweetAlert provides a nice replacement for standard JavaScript modals. You can include it in your HTML via a CDN (content delivery network) and begin use.
```HTML
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
```
The syntax is as such: ```swal(title, subtitle, messageType)```
```javascript
swal("Oops!", "Something went wrong on the page!", "error");
```
The above code will produce the following popup:
![SweetAlert Example](https://ludu-assets.s3.amazonaws.com/lesson-content/rWqOoQXgDrSVSMrAKiZ9)
SweetAlert is by no means the only substitute for standard modals, but it is clean and easy to implement.
#### More Information:
* <a href='https://developer.mozilla.org/en-US/docs/Web/API/Window/alert' target='_blank' rel='nofollow'>MDN window.alert()</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm' target='_blank' rel='nofollow'>MDN window.confirm()</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt' target='_blank' rel='nofollow'>MDN window.prompt()</a>

View File

@ -0,0 +1,174 @@
---
title: Promises
---
## Promises
JavaScript is single threaded, meaning that two bits of script cannot run at the same time; they have to run one after another. A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.
```javascript
var promise = new Promise(function(resolve, reject) {
// do thing, then…
if (/* everything worked */) {
resolve("See, it worked!");
}
else {
reject(Error("It broke"));
}
});
```
## A Promise exists in one of these states
- Pending: initial state, neither fulfilled nor rejected.
- Fulfilled: operation completed successfully.
- Rejected: operation failed.
The Promise object works as proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.
## Using 'Then' (Promise Chaining)
To take several asynchronous calls and synchronize them one after the other, you can use promise chaining. This allows using a value from the first promise in later subsequent callbacks.
```javascript
Promise.resolve('some')
.then(function(string) { // <-- This will happen after the above Promise resolves (returning the value 'some')
return new Promise(function(resolve, reject) {
setTimeout(function() {
string += 'thing';
resolve(string);
}, 1);
});
})
.then(function(string) { // <-- This will happen after the above .then's new Promise resolves
console.log(string); // <-- Logs 'something' to the console
});
```
## Promise API
There are 4 static methods in the Promise class:
- Promise.resolve
- Promise.reject
- Promise.all
- Promise.race
## Promises can be chained together
When writing Promises to solve a particular problem, you can chain them together to form logic.
```javascript
var add = function(x, y) {
return new Promise((resolve,reject) => {
var sum = x + y;
if (sum) {
resolve(sum);
}
else {
reject(Error("Could not add the two values!"));
}
});
};
var subtract = function(x, y) {
return new Promise((resolve, reject) => {
var sum = x - y;
if (sum) {
resolve(sum);
}
else {
reject(Error("Could not subtract the two values!"));
}
});
};
// Starting promise chain
add(2,2)
.then((added) => {
// added = 4
return subtract(added, 3);
})
.then((subtracted) => {
// subtracted = 1
return add(subtracted, 5);
})
.then((added) => {
// added = 6
return added * 2;
})
.then((result) => {
// result = 12
console.log("My result is ", result);
})
.catch((err) => {
// If any part of the chain is rejected, print the error message.
console.log(err);
});
```
This is useful for following a *Functional Programming* paradigm. By creating
functions for manipulating data you can chain them together to assemble a final
result. If at any point in the chain of functions a value is *rejected* the chain
will skip to the nearest `catch()` handler.
For more information on Functional Programming: <a href='https://en.wikipedia.org/wiki/Functional_programming' target='_blank' rel='nofollow'>Functional Programming</a>
## Function Generators
In recent releases, JavaScript has introduced more ways to natively handle Promises. One such way is the function generator. Function generators are "pausable" functions. When used with Promises, generators can make using a lot easier to read and appear "synchronous".
```javascript
const myFirstGenerator = function* () {
const one = yield 1;
const two = yield 2;
const three = yield 3;
return 'Finished!';
}
const gen = myFirstGenerator();
```
Here's our first generator, which you can see by the `function*` syntax. The `gen` variable we declared will not run `myFirstGenerator`, but instead will "this generator is ready to use".
```javascript
console.log(gen.next());
// Returns { value: 1, done: false }
```
When we run `gen.next()` it will unpause the generator and carry on. Since this is the first time we have called `gen.next()` it will run `yield 1` and pause until we call `gen.next()` again. When `yield 1` is called, it will return to us the `value` that was yielded and whether or not the generator is `done`.
```javascript
console.log(gen.next());
// Returns { value: 2, done: false }
console.log(gen.next());
// Returns { value: 3, done: false }
console.log(gen.next());
// Returns { value: 'Finished!', done: true }
console.log(gen.next());
// Will throw an error
```
As we keep calling `gen.next()` it will keep going onto the next `yield` and pausing each time. Once there are no more `yield`'s left, it will proceed to run the rest of the generator, which in this case simply returns `'Finished!'`. If you call `gen.next()` again, it will throw an error as the generator is finished.
Now, imagine if each `yield` in this example was a `Promise`, the code itself would appear extremely synchronous.
### Promise.all(iterable) is very usefull for multiple request to different source
The Promise.all(iterable) method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects.
```javascript
var promise1 = Promise.resolve(catSource);
var promise2 = Promise.resolve(dogSource);
var promise3 = Promise.resolve(cowSource);
Promise.all([promise1, promise2, promise3]).then(function(values) {
console.log(values);
});
// expected output: Array ["catData", "dogData", "cowData"]
```
### More Information
For more information on promises: <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise' target='_blank' rel='nofollow'>Promises</a>

View File

@ -0,0 +1,105 @@
---
title: Prototypes
---
## Prototypes
JavaScript is a prototype-based language, therefore understanding the prototype object is one of the most important concepts which JavaScript practitioners need to know. This article will give you a short overview of the Prototype object through various examples. Before reading this article, you will need to have a basic understanding of the [`this` reference in JavaScript](/src/pages/javascript/this-reference/index.md).
### Prototype object
For the sake of clarity, let's examine the following example:
```javascript
function Point2D(x, y) {
this.x = x;
this.y = y;
}
```
As `Point2D` function is declared, a default property named `prototype` will be created for it (note that, in JavaScript, a function is also an object). The `prototype` property is an object which contains a `constructor` property and its value is `Point2D` function: `Point2D.prototype.constructor = Point2D`. And when you call `Point2D` with `new` keyword, *newly created objects will inherit all properties from* `Point2D.prototype`. To check that, you can add a method named `move` into `Point2D.prototype` as follows:
```javascript
Point2D.prototype.move = function(dx, dy) {
this.x += dx;
this.y += dy;
}
var p1 = new Point2D(1, 2);
p1.move(3, 4);
console.log(p1.x); // 4
console.log(p1.y); // 6
```
The `Point2D.prototype` is called **prototype object** or **prototype** of `p1` object and for any other object created with `new Point2D(...)` syntax. You can add more properties to `Point2D.prototype` object as you like. The common pattern is declare methods to `Point2D.prototype` and other properties will be declared in constructor function.
Built-in objects in JavaScript are constructed in a similar manner. For example:
- Prototype of objects created with `new Object()` or `{}` syntax is `Object.prototype`.
- Prototype of arrays created with `new Array()` or `[]` syntax is `Array.prototype`.
- And so on with other built-in objects such as `Date` and `RegExp`.
`Object.prototype` is inherited by all objects and it has no prototype (its prototype is `null`).
### Prototype chain
The prototype chain mechanism is simple: When you access a property `p` on object `obj`, the JavaScript engine will search this property inside `obj` object. If the engine fails to search, it continues searching in the prototype of `obj` object and so on until reaching `Object.prototype`. If after the search has finished, and nothing has been found the result will be `undefined`.
For example:
```javascript
var obj1 = {
a: 1,
b: 2
};
var obj2 = Object.create(obj1);
obj2.a = 2;
console.log(obj2.a); // 2
console.log(obj2.b); // 2
console.log(obj2.c); // undefined
```
In above snippet, the statement `var obj2 = Object.create(obj1)` will create `obj2` object with prototype `obj1` object. In other words, `obj1` becomes the prototype of `obj2` instead of `Object.prototype` by default. As you can see, `b` is not a property of `obj2`, you can still access it via the prototype chain. For `c` property, however, you get `undefined` value because it can't be found in `obj1` and `Object.prototype`.
### Classes
In ES2016, we now get to use the `Class` keyword as well as the methods mentioned above to manipulate `prototype`. The JavaScript `Class` appeals to developers from OOP backgrounds, but it's essentially doing the same thing as above.
```javascript
class Rectangle {
constructor(height, width) {
this.height = height
this.width = width
}
get area() {
return this.calcArea()
}
calcArea() {
return this.height * this.width
}
}
const square = new Rectangle(10, 10)
console.log(square.area) // 100
```
This is basically the same as:
```javascript
function Rectangle(height, width) {
this.height = height
this.width = width
}
Rectangle.prototype.calcArea = function calcArea() {
return this.height * this.width
}
```
The `getter` and `setter` methods in classes bind an Object property to a function that will be called when that property is looked up. It's just syntactic sugar to help make it easier to _look up_ or _set_ properties.
**Further Reading:**
* [MDN: Object prototypes](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes)

View File

@ -0,0 +1,100 @@
---
title: Random Method
---
## Random Method
The JavaScript `Math.random()` method is an excellent built-in method for producing random numbers. When `Math.random()` is executed, it returns a random number that can be anywhere between 0 and 1. The 0 is included and 1 is excluded.
### Generating a random floating point number between 0 and 1
The `Math.random()` method will return a floating point (decimal) number greater than or equal to 0 and less than (but never equal to) 1. In other words `0 <= x < 1`. For example:
```JavaScript
console.log(Math.random());
// 0.7069207248635578
console.log(Math.random());
// 0.765046694794209
console.log(Math.random());
// 0.14069121642698246
```
(Of course, the numbers returned will be different every time. This will be assumed for all following examples - different results will happen on each pass.)
To get a random number between a larger range multiply the result of `Math.random()` by a number.
### Generating a random floating point number between 0 and a specified max
Usually you do not need random numbers between 0 and 1 - you need larger numbers or even integers.
For example, if you want a random floating point number between 0 and 10, you could use:
```JavaScript
var x = Math.random()*10;
console.log(x);
// 4.133793901445541
```
### Generating a random floating point number within a range
If you need a random floating point number that ranges between two specific numbers, you could do something like this:
```JavaScript
var min = 83.1;
var max = 193.36;
var x = Math.random()*(max - min)+min;
console.log(x);
// 126.94014012699063
```
### Generating a random integer between 0 and a max
Often you need integers. To do this you will have to use some other methods from the `Math` object, `Math.floor()` (rounds down to the nearest integer) and `Math.ceil()` (rounds up to the nearest integer).
For example, if you need to select randomly from an array of 10 elements, you would need a random number between 0 and 9 inclusive (remember that arrays are zero indexed).
```JavaScript
var x = Math.floor(Math.random()*10);
console.log(x);
// 7
```
(Remember that `Math.random()` will never return exactly 1, so `Math.random()*10` will never return exactly 10. This means that after rounding down, the result will always be 9 or less.)
### Generating a random integer between 1 and a max
If you need a random number with the minimum number being 1 (for example picking a random day in January) you could use the `Math.ceil()` method.
```JavaScript
var x = Math.ceil(Math.random()*31);
console.log(x);
// 23
```
Another way would have been to use the previous function (using `Math.floor()`) and add 1 to it:
```JavaScript
var x = Math.floor(Math.random()*31)+1;
console.log(x);
// 17
```
### Generating a random integer within a range
Lastly, occasionally you need a random integer between two specific integers. For example, if you are trying to pick raffle tickets and you know the numbers of the lowest and largest number:
```JavaScript
var min = 1718;
var max = 3429;
var x = Math.floor(Math.random()*(max-min+1)+min);
console.log(x);
//2509
```
### How random is Math.random()?
It may be pointed out that the number returned by `Math.random()` is a pseudo-random number as no computer can generate a truly random number, that exhibits randomness over all scales and over all sizes of data sets. However, the pseudo-random number generated by `Math.random()` is usually sufficient for the needs of nearly any program you may write. The not-truly-randomness only becomes apparent in astronomically large number sets or when uncommonly precise decimals are needed.
### More Information:
- Documentation: <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random' target='_blank' rel='nofollow'>MDN</a>

View File

@ -0,0 +1,98 @@
---
title: Regular Expressions Reference
---
## Regular Expressions Reference
In JavaScript, regular expressions are a shorthand used to match the desired part of a string. These are beneficial when trying to manipulate or validate strings used in your code.
### Syntax
Regular expressions are made up of two parts - the `pattern` and the `flags` (optional). The pattern is written between two forward slashes, followed by the optional flags: `var exp = /pattern/flags`.
#### Patterns
The use of alphanumeric (A-Z, a-z, 0-9) characters makes for a straightforward match. However, the real power of regular expressions comes with character classes.
Say, for example, you want to all the places a string that has a number from 0-9. Rather than explicitly calling out `/[0-9]/`, you can use the special character class of `/\d/`. The backslash escapes the `d` character (so don't match the letter `d`), but instead uses the special matching abilities of `\d`.
This same principle applies to non-numeric characters, white space, and other broad matching groups. Regular expressions can become even more sophisticated with the use of certain modifiers, such as the `+` character.
This quantifier allows you to match the preceding character in your pattern one or more times. `/s+/` would match the `s` in `desert` and both `s`'s in `dessert`!
There are plenty more modifiers that allow your pattern to match whatever you might need. See the More Information section below to see all the possible character options for use in regular expressions.
#### Flags
There are 5 flags you can use to apply specific rules to the whole regular expression you are writing. They are:
`g` - the global match; this allows you to match all instances of your expression, rather than stopping after the first occurrence.
`i` - the ignore case match (self-explanatory)
`m` - the multi-line match; this applies your pattern to each line as new; if you are searching for a line that starts with a particular pattern, this does so for all lines, rather than just the first one
`u` - the Unicode match; this signals to read your pattern as Unicode rather than plain text
`y` - the sticky match; this matches your pattern only starting at the index found in the `RegExp.lastIndex` property
### Creating a regular expression
A regular expression is a type of object. It can either be constructed
with the RegExp constructor or written as a literal value by enclosing the
pattern in forward slash ( / ) characters.
```
var re1 = new RegExp (" abc ") ;
var re2 = / abc /;
```
Both of these regular expression objects represent the same pattern: an
a character followed by a b followed by a c.
### The RegExp Object
`RegExp` is a constructor that creates an object from the regular expression pattern you create. In addition to the literal notation described above, you can also use the constructor format to create a regular expression: `new RegExp(pattern[, flags])`
### Testing for matches
```
console . log (/ abc /. test (" abcde ") );
// → true
console . log (/ abc /. test (" abxde ") );
// → false
```
### Matching a set of characters
```
console . log (/[0123456789]/. test (" in 1992") );
// → true
console . log (/[0 -9]/. test (" in 1992") );
// → true
```
### Choice patterns
```
var animalCount = /\ b \ d + ( pig | cow | chicken )s ?\ b /;
console . log ( animalCount . test ("15 pigs ") );
// → true
console . log ( animalCount . test ("15 pigchickens ") );
// → false
```
#### Methods
You will most likely use regular expressions in `String` methods, such as `String.replace()`, but there are a handful of methods that belong to the `RegExp` object.
For example, `RegExp.test()` will return a Boolean for whether there exists a match between the regular expression pattern and the string in question. `RegExp.toString()` will turn the expression object into a string, which can be handy when running tests on your code.
The first argument can also be a regular expression, in which case thefirst match of the regular expression is replaced. When a g option (for global) is added to the regular expression, all matches in the string will be replaced, not just the first.
```
console . log (" Borobudur ". replace (/[ ou ]/ , "a ") );
// → Barobudur
console . log (" Borobudur ". replace (/[ ou ]/g , "a ") );
// → Barabadar
```
### More Information:
* <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp" target='_blank' rel='nofollow'>Here you can read</a> about all the pattern match characters, object properties, see some examples and more.
* <a href="https://regex101.com/" target='_blank' rel='nofollow'>Here is a great site</a> that lets you test out regular expression patterns in real-time, save your favorites and explore patterns made by others.

View File

@ -0,0 +1,38 @@
---
title: Rest Parameters
---
## Rest Parameters
In ES6, the rest paramter syntax `...` allows you to gather up an indefinite number of arguments into an array.
Even though they look the same, it does the opposite of the spread operator, which takes every item from an iterable and spreads them out into their individual values.
### Syntax
```js
function myFunc(...args) {
console.log(args);
}
myFunc( 1, 2, 3, 4, 5); // [1,2,3,4,5]
```
You can prefix a function's last parameter with `...` when you want to do something with the initial paramters and then treat all of the remaining parameters differently.
```js
function convertCurrency(rate, fee, ...amounts) {
return amounts.map(amount => (amount * rate) + fee);
}
convertCurrency(0.89, 2.5, 100, 250, 75, 150, 300); // [ 91.5, 225, 69.25, 136, 269.5 ]
```
The `...` lets you gather up the rest of the arguments, if there are any, into an array.
### The difference between rest parameters and the arguments object
`arguments` is an array-like object, available inside functions, that contains the arguments passed to those functions. It's called "array-like" because it doesn't have all of an array's built in methods, such as `.forEach()` and `.map()`.
The rest parameters are an array, with all of the array methods included.

View File

@ -0,0 +1,83 @@
---
title: Return Statement
---
## Introduction
When a **return** statement is called in a function, the execution of this function is stopped. If specified, a given value is returned to the function caller. If the expression is omitted, `undefined` is returned instead.
```js
return expression;
```
Functions can return:
* Primitive values (string, number, boolean, etc.)
* Object types (arrays, objects, functions, etc.)
Never return something on a new line without using parentheses. This is a JavaScript quirk and the result will be undefined. Try to always use parentheses when returning something on multiple lines.
```javascript
function foo() {
return
1;
}
function boo() {
return (
1
);
}
foo(); --> undefined
boo(); --> 1
```
## Examples
The following function returns the square of its argument, **x**, where **x** is a number.
```js
function square(x) {
return x * x;
}
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/C7VT/0' target='_blank' rel='nofollow'>Run Code</a>
The following function returns the product of its arguments, **arg1** and **arg2**.
```js
function myfunction(arg1, arg2){
var r;
r = arg1 * arg2;
return(r);
}
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/C7VU/0' target='_blank' rel='nofollow'>Run Code</a>
When a function `return`s a value, the value can be assigned to a variable using the assigment operator (`=`). In the example below, the function returns the square of the argument. When the function resolves or ends, its value is the `return`ed value. The value is then assigned to the variable `squared2`.
```javascript
function square(x) {
return x * x;
}
let squared2 = square(2); // 4
```
If there is no explicit return statement, meaning the function is missing the `return` keyword, the function automatically returns `undefined`. In the following example, the `square` function is missing the `return` keyword. When the result of calling the function is assigned to a variable, the variable has a value of `undefined`.
```javascript
function square(x) {
let y = x * x;
}
let squared2 = square(2); // undefined
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":rocket:") <a href='https://repl.it/M8BE' target='_blank' rel='nofollow'>Run Code</a>
#### More Information:
<a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return' target='_blank' rel='nofollow'>MDN link</a>
<a href='https://msdn.microsoft.com/en-us/library/22a685h9.aspx' target='_blank' rel='nofollow'>MSDN link</a>

View File

@ -0,0 +1,126 @@
---
title: Scopes
---
If you've been programming in JavaScript for a while, you've undoubtedly run into a concept known as `scope`. What is `scope`? Why should you take the time to learn it?
In programmer speak, `scope` is the **current context of execution**. Confused? Let's take a look at the following piece of code:
var foo = 'Hi, I am foo!';
var baz = function () {
var bar = 'Hi, I am bar too!';
console.log(foo);
}
baz(); // Hi, I am foo!
console.log(bar); // ReferenceError...
This is a simple example, but it does a good job of illustrating what is known as _Lexical scope_. JavaScript, and almost every other programming language has a _Lexical scope_. There is another kind of scope known as _Dynamic scope_, but we won't be discussing that.
Now, the term _Lexical scope_ sounds fancy, but as you will see it's really simple in principle. In a Lexical Scope, there are two kinds of scopes: the _global scope_ and a _local scope_.
Before you type the first line of code in your program, a _global scope_ is created for you. This contains all the variables that you declare in your program **outside any functions**.
In the example above, the variable `foo` is in the global scope of the program, while the variable `bar` is declared inside a function and is therefore **in the local scope of that function**.
Lets break down the example line by line. While you might be confused at this point, I promise you will have a much better understanding by the time you finish reading this.
On line 1 we are declaring the variable `foo`. Nothing too fancy here. Lets call this a left-hand size (LHS) reference to `foo`, because we are assigning a value to `foo` and it's on the left-hand side of the `equal` sign.
On line 3, we are declaring a function and assigning it to variable `baz`. This is another LHS reference to `baz`. We are assigning a value to it (remember, functions are values too!). This function is then called on line 8\. This is a RHS, or a right-hand side reference to `baz`. We are retrieveing `baz`'s value, which in this case is a function and then invoking it. Another RHS reference to `baz` would be if we assigned its value to another variable, for example `foo = baz`. This would be a LHS reference to `foo` and a RHS reference to `baz`.
The LHS and RHS references might sound confusing, but they are important for discussing scope. Think of it this way: a LHS reference is assigning a value to the variable, while a RHS reference is retrieving the value of the variable. They're just a shorter and more convenient way of saying 'retrieving the value' and 'assigning a value'.
Let's now breakdown what's happening inside the function itself.
When the compiler compiles the code inside a function, it enters the function's **local scope**.
On line 4, the variable `bar` is declared. This is a LHS reference to `bar`. On the next line, we have a RHS reference to `foo` inside the `console.log()`. Remember, we are retrieving `foo`'s value and then passing it as an argument to the method `console.log()`.
When we have a RHS reference to `foo`, the compiler looks for the declaration of the variable `foo`. The compiler doesn't find it in the function itself, or the **function's local scope** so it **goes up one level: to the global scope**.
At this point you're probably thinking that scope has something to do with variables. That is correct. A scope can be thought of as a container for variables. All variables that are created within a local scope are only accessible in that local scope. However, all local scopes can access the global scope. (I know you're probably even more confused right now, but just bear with me for a few more paragraphs).
So the compiler goes up to the global scope to find a LHS reference to the variable `foo`. It finds one on line 1, so it retrieves the value from the LHS reference, which is a string: `'Hi, I am foo!'`. This string is sent to the `console.log()` method, and outputted to the console.
The compiler has finished executing the code inside the function, so we come back out to line 9\. On line 9, we have a RHS reference for the variable `bar`.
Now, `bar` was declared in the local scope of `baz`, but there is a RHS reference for `bar` in the global scope. Since there is no LHS reference for `bar` in the global scope, the compiler can't find a value for `bar` and throws a ReferenceError.
But, you might ask, if the function can look outside itself for variables, or a local scope can peek into the global scope to find LHS references, why can't the global scope peek into a local scope? Well that's how lexical scope works!
... // global scope
var baz = function() {
... // baz's scope
}
... /// global scope
This is the same code from above which illustrates the scope. This forms a sort of hierarchy that goes up to the global scope:
`baz -> global`.
So, if there is a RHS reference for a variable inside `baz`'s scope, it can be fulfilled by a LHS reference for that variable in the global scope. But the opposite is **not true**.
What if we had another function inside `baz`?
... // global scope
var baz = function() {
... // baz's scope
var bar = function() {
... // bar's scope.
}
}
... /// global scope
In this case, the hierarchy or the **scope chain** would look like this:
`bar -> baz -> global`
Any RHS references inside `bar`'s local scope can be fullfilled by LHS references in the global scope or `baz`'s scope, but a RHS reference in `baz`'s scope cannot be fullfilled by a LHS reference in `bar`'s scope.
**You can only traverse down a scope chain, not up.**
There are other two important things you should know about JavaScript scopes.
1. Scopes are declared by functions, not by blocks.
2. Functions can be forward-referenced, variables can't.
Observe (each comment describes scope at the line that it's written on):
```
// outer() is in scope here because functions can be forward-referenced
function outer() {
// only inner() is in scope here
// because only functions are forward-referenced
var a = 1;
//now 'a' and inner() are in scope
function inner() {
var b = 2
if (a == 1) {
var c = 3;
}
// 'c' is still in scope because JavaScript doesn't care
// about the end of the 'if' block, only function inner()
}
// now b and c are out of scope
// a and inner() are still in scope
}
// here, only outer() is in scope
```
# References
1. <a href='https://github.com/getify/You-Dont-Know-JS/tree/master/scope%20%26%20closures' target='_blank' rel='nofollow'>Scopes and Closures</a> by Kyle Simpson. It goes into more details of how the scope mechanism works, and also has a superficial description of how the JavaScript compiler works, so if you're interested in that, definitely give it a read! It's free on GitHub and can be bought from O'Reilly.
2. <a href="https://www.amazon.com/Secrets-JavaScript-Ninja-John-Resig/dp/1617292850/ref=pd_lpo_sbs_14_img_0?_encoding=UTF8&psc=1&refRID=YMC2TB2C0DFHTQ3V62CA" target='_blank'>Secrets of the JavaScript Ninja</a> by John Resig and Bear Bibeault. A great guide for a more in-depth understanding of JavaScript.

View File

@ -0,0 +1,39 @@
---
title: Semicolons
---
Semicolons are not required in Javascript. This is because Javascript has a feature called "Automatic Semicolon Insertion" or ASI for short. ASI puts semicolons in your Javascript for you. It is always active by default and it's a part of the language and can not be disabled.
ASI has a set of rules it uses to determine where it should insert semicolons. If there is already a semicolon in place, it won't change anything. See <a href='http://stackoverflow.com/a/2846298/3467946' target='_blank' rel='nofollow'>this StackOverflow answer</a> for more information on how ASI works.
There is only one case where ASI fails: when a line starts with an opening bracket `(`. To avoid this causing errors, when a line starts with an opening bracket, you can put a semicolon at the beginning of the line that has the opening bracket:
```js
;(function() {
console.log('Hi!')
})
```
Note that this is only required if you don't use semicolons.
A consistent coding style makes code more readable. Decide whether you will or won't use semicolons, and do so everywhere.
## Errors you might run into
When Javascript was first made it was meant to aid beginners to get into programming. Nobody wants to be searching for a dang semi-colon in their code when they first start programming. So the choice of semi-colons was implemented, as stated above they are technically there.
For example:
```javasctipt
function foo(x) {
return
function(y) {
return x + y;
}
}
let z = foo(10);
z(10)// TypeError z is not a function
// Because of Automatic Semicolon Insertion, our inner function does not exist.
```
Javasctipt will implement semi-colons where they are expected.
### Other resources
<a href='http://blog.izs.me/post/2353458699/an-open-letter-to-javascript-leaders-regarding' target='_blank' rel='nofollow'>An Open Letter to JavaScript Leaders Regarding Semicolons</a>

View File

@ -0,0 +1,88 @@
---
title: Creating a Singleton in JavaScript
---
## Creating a Singleton in JavaScript
A singleton is an object that only allows one instance of itself to be created and allows a global point of access to it. The singleton design pattern can be useful if you have some data that should remain the same throughout your application.
### Let's Get Started
Let's create an object with an immediately-invoked function expression (or _IIFE_, pronounced "iffy") that will give us the effect of a singleton.
```
var singletonFn = (function(){ // Created IIFE Function
var dataCounter = 0;
return { // Any code inside this return stuff will be accessible directly using objectname.
getDataCounter: function(){
return dataCounter;
},
setDataCounter: function(val){
dataCounter = val;
},
fishNames: ["SimpleFish"] // Can create variables, arrays, etc.
}
})();
console.log(singletonFn.getDataCounter()); // 0 by default
singletonFn.setDataCounter(20);
console.log(singletonFn.getDataCounter()); // 20
console.log(singletonFn.fishNames); // ["SimpleFish"]
```
Here's another example of a singleton:
```
var Person;
(function() {
let instance;
Person = function(fName, lName, job) {
// constructor
this.fName = fName || 'John';
this.lName = lName || 'Doe';
this.job = job || 'Software Engineer';
if (!instance) {
instance = this;
}
this.getFullName = function () {
return this.fName + ' ' + this.lName;
}
this.getJob = function () {
return this.job;
}
this.print = function () {
console.log(this.getFullName() + ' ' + this.getJob());
}
return instance;
}
})();
//initialize these "guys" but they point to the same object
var guy1 = new Person();
var guy2 = new Person();
// proof that they're the same instance
guy1.print(); // "John Doe Software Engineer"
guy2.print(); // "John Doe Software Engineer"
console.log(guy1 == guy2); //true
// modify guy2 and see that guy1 has changed as well
guy2.fName = 'Jane';
guy2.lName = 'Doo';
guy2.job = 'Project Manager';
guy1.print(); // "Jane Doo Project Manager"
guy2.print(); // "Jane Doo Project Manager"
```

View File

@ -0,0 +1,150 @@
---
title: Spread syntax
---
## Spread syntax
Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero are expected.
### Syntax
For function calls:
```
myFunction(...iterableObj);
```
For array literals or strings:
```
[...iterableObj, '4', 'five', 6];
```
### Examples
#### Spread in function calls
#### Replace apply
It is common to use `Function.prototype.apply` in cases where you want to use the elements of an array as arguments to a function.
```
function myFunction(x, y, z) { }
var args = [0, 1, 2];
myFunction.apply(null, args);
```
With spread syntax the above can be written as:
```
function myFunction(x, y, z) { }
var args = [0, 1, 2];
myFunction(...args);
```
Any argument in the argument list can use spread syntax and it can be used multiple times.
```
function myFunction(v, w, x, y, z) { }
var args = [0, 1];
myFunction(-1, ...args, 2, ...[3]);
```
### Apply for new
When calling a constructor with `new`, it's not possible to **directly** use an array and `apply` (`apply` does a `[[Call]]` and not a `[[Construct]]`). However, an array can be easily used with new thanks to spread syntax:
```
var dateFields = [1970, 0, 1]; // 1 Jan 1970
var d = new Date(...dateFields);
```
To use new with an array of parameters without spread syntax, you would have to do it **indirectly** through partial application:
```
function applyAndNew(constructor, args) {
function partial () {
return constructor.apply(this, args);
};
if (typeof constructor.prototype === "object") {
partial.prototype = Object.create(constructor.prototype);
}
return partial;
}
function myConstructor () {
console.log("arguments.length: " + arguments.length);
console.log(arguments);
this.prop1="val1";
this.prop2="val2";
};
var myArguments = ["hi", "how", "are", "you", "mr", null];
var myConstructorWithArguments = applyAndNew(myConstructor, myArguments);
console.log(new myConstructorWithArguments);
// (internal log of myConstructor): arguments.length: 6
// (internal log of myConstructor): ["hi", "how", "are", "you", "mr", null]
// (log of "new myConstructorWithArguments"): {prop1: "val1", prop2: "val2"}
```
### Spread in array literals
#### A more powerful array literal
Without spread syntax, to create a new array using an existing array as one part of it, the array literal syntax is no longer sufficient and imperative code must be used instead using a combination of push, splice, concat, etc. With spread syntax this becomes much more succinct:
```
var parts = ['shoulders', 'knees'];
var lyrics = ['head', ...parts, 'and', 'toes'];
// ["head", "shoulders", "knees", "and", "toes"]
```
Just like spread for argument lists, `...` can be used anywhere in the array literal and it can be used multiple times.
### Copy an array
```
var arr = [1, 2, 3];
var arr2 = [...arr]; // like arr.slice()
arr2.push(4);
// arr2 becomes [1, 2, 3, 4]
// arr remains unaffected
```
> **Note**: Spread syntax effectively goes one level deep while copying an array. Therefore, it may be unsuitable for copying multidimensional arrays as the following example shows (it's the same with Object.assign() and spread syntax).
```
var a = [[1], [2], [3]];
var b = [...a];
b.shift().shift(); // 1
// Now array a is affected as well: [[], [2], [3]]
```
### A better way to concatenate arrays
`Array.concat` is often used to concatenate an array to the end of an existing array. Without spread syntax this is done as:
```
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
// Append all items from arr2 onto arr1
arr1 = arr1.concat(arr2);
```
With spread syntax this becomes:
```
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1 = [...arr1, ...arr2];
```
`Array.unshift` is often used to insert an array of values at the start of an existing array. Without spread syntax this is done as:
```
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
// Prepend all items from arr2 onto arr1
Array.prototype.unshift.apply(arr1, arr2) // arr1 is now [3, 4, 5, 0, 1, 2]
```
With spread syntax this becomes:
```
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1 = [...arr2, ...arr1]; // arr1 is now [3, 4, 5, 0, 1, 2]
```

View File

@ -0,0 +1,94 @@
---
title: Array Destructuring
---
# Array Destructuring
Destructuring is a convenient way of extracting multiple values from data stored in Arrays. It can be used in locations that receive data (such as the left-hand side of an assignment). This feature is introduced in `ECMAScript 6`.
How to extract the values is specified via patterns (read on for examples).
### Basic variable assignment
```
var names = ['neel', 'meet', 'darshan'];
var [nameOne, nameTwo, nameThree] = names;
console.log(nameOne); // "neel"
console.log(nameTwo); // "meet"
console.log(nameThree); // "darshan"
```
### Assignment separate from declaration
A variable can be assigned its value via destructuring separate from the variable's declaration.
```
var a, b;
[a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2
```
### Default values
A variable can be assigned a default, in the case that the value unpacked from the array is `undefined`.
```
var a, b;
[a=5, b=7] = [1];
console.log(a); // 1
console.log(b); // 7
```
### Parsing an array returned from a function
It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise.
In this example, `getNames()` returns the values `['neel', 'meet']` as its output, which can be parsed in a single line with destructuring.
```
function getNames() {
return ['neel', 'meet'];
}
var neel, meet;
[nameOne, nameTwo] = getNames();
console.log(nameOne); // neel
console.log(nameTwo); // meet
```
### Ignoring some returned values
You can ignore return values that you're not interested in:
```
function getNames() {
return ['neel', 'meet', 'darshan'];
}
var [nameOne, , nameThree] = getNames();
console.log(nameOne); // neel
console.log(nameThree); // darshan
```
You can also ignore all returned values:
```
[,,] = getNames();
```
### Assigning the rest of an array to a variable
When destructuring an array, you can unpack and assign the remaining part of it to a variable using the rest pattern:
```
var [a, ...b] = [1, 2, 3];
console.log(a); // 1
console.log(b); // [2, 3]
```
Note that a `SyntaxError` will be thrown if a trailing comma is used on the left-hand side with a rest element:
```
var [a, ...b,] = [1, 2, 3];
// SyntaxError: rest element may not have a trailing comma
```
See also: <a>**Array Destructuring**</a> | <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Array_destructuring' target='_blank' rel='nofollow'>MDN</a>

View File

@ -0,0 +1,22 @@
---
title: Array from
---
## Array from
The 'Array.from()' method creates a new Array instance from an array-like or iterable object.
### Syntax:
'''
Array.from(arrayLike[, mapFn[, thisArg]])
'''
### Example:
'''
Array.from('foo');
// ["f", "o", "o"]
'''
#### More Information:
[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)

View File

@ -0,0 +1,34 @@
---
title: Array isArray
---
The `Array.isArray()` method returns `true` if an object is an array, `false` if it is not.
## Syntax
Array.isArray(obj)
### Parameters
**obj** The object to be checked.
<a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray' target='_blank' rel='nofollow'>MDN link</a> | <a href='https://msdn.microsoft.com/en-us/LIBRary/ff848265%28v=vs.94%29.aspx' target='_blank' rel='nofollow'>MSDN link</a>
## Examples
// all following calls return true
Array.isArray([]);
Array.isArray([1]);
Array.isArray(new Array());
// Little known fact: Array.prototype itself is an array:
Array.isArray(Array.prototype);
// all following calls return false
Array.isArray();
Array.isArray({});
Array.isArray(null);
Array.isArray(undefined);
Array.isArray(17);
Array.isArray('Array');
Array.isArray(true);
Array.isArray(false);
Array.isArray({ __proto__: Array.prototype });

View File

@ -0,0 +1,27 @@
---
title: Array Length
---
## Array Length
`length` is a property of arrays in JavaScript that returns or sets the number of elements in a given array.
The `length` property of an array can be returned like so.
```js
let desserts = ["Cake", "Pie", "Brownies"];
console.log(desserts.length); // 3
```
The assignment operator, in conjunction with the `length` property, can be used to set then number of elements in an array like so.
```js
let cars = ["Saab", "BMW", "Volvo"];
cars.length = 2;
console.log(cars.length); // 2
```
#### More Information:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length

View File

@ -0,0 +1,26 @@
---
title: Array of
---
## Array of
The Array.of() method creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.
Syntax:
```javascript
Array.of(element0[, element1[, ...[, elementN]]])
```
## Example
```javascript
Array.of(7); // [7] - creates an array with a single element
Array.of(1, 2, 3); // [1, 2, 3]
Array(7); // [ , , , , , , ] - creates an empty array with a length property of 7
Array(1, 2, 3); // [1, 2, 3]
```
#### More Information:
For more information visit [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/of)

View File

@ -0,0 +1,42 @@
---
title: Array.prototype.concat
---
## Array.prototype.concat
The 'concat' method returns a new array consisting of the elements of the array on which you call it, followed by the elements of the arguments in the order they are passed.
You can pass multiple arguments to the 'concat' method. The arguments can be arrays, or data types like booleans, strings, and numbers.
### Syntax
```javascript
const newArray = array.concat(value1, value2, value3...);
```
### Examples
#### Concatenating two arrays
```javascript
var cold = ['Blue', 'Green', 'Purple'];
var warm = ['Red', 'Orange', 'Yellow'];
var result = cold.concat(warm);
console.log(result);
// results in ['Blue', 'Green', 'Purple', 'Red', 'Orange', 'Yellow'];
```
#### Concatenating value to an array
```javascript
const odd = [1, 3, 5, 7, 9];
const even = [0, 2, 4, 6, 8];
const oddAndEvenAndTen = odd.concat(even, 10);
console.log(oddAndEvenAndTen);
// results in [1, 3, 5, 7, 9, 0, 2, 4, 6, 8, 10];
```
#### More Information:
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat)

View File

@ -0,0 +1,15 @@
---
title: Array.prototype.copyWithin
---
## Array.prototype.copyWithin
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/javascript/standard-objects/array/array-prototype-copywithin/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -0,0 +1,15 @@
---
title: Array.prototype.entries
---
## Array.prototype.entries
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/javascript/standard-objects/array/array-prototype-entries/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -0,0 +1,68 @@
---
title: Array.prototype.every
---
The `every()` method tests whether all elements in the array pass the test implemented by the provided function.
**Syntax**
```javascript
arr.every(callback[, thisArg])
```
## Parameters
* **callback** Function to test for each element, taking three arguments:
* **currentValue** (required)
The current element being processed in the array.
* **index** (optional)
The index of the current element being processed in the array.
* **array** (optional)
The array every was called upon.
* **thisArg** Optional. Value to use as this when executing callback.
<a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every' target='_blank' rel='nofollow'>MDN link</a> | <a href='https://msdn.microsoft.com/en-us/LIBRary/ff679981%28v=vs.94%29.aspx' target='_blank' rel='nofollow'>MSDN Link</a>
## Description
The `every` method calls the `callback` function one time for each array element, in ascending index order, until the `callback` function returns false. If an element that causes `callback` to return false is found, the every method immediately returns `false`. Otherwise, the every method returns `true`.
The callback function is not called for missing elements of the array.
In addition to array objects, the every method can be used by any object that has a length property and that has numerically indexed property names. `every` does not mutate the array on which it is called.
## Examples
```javascript
function isBigEnough(element, index, array) {
return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough); // false
[12, 54, 18, 130, 44].every(isBigEnough); // true
// Define the callback function.
function CheckIfEven(value, index, ar) {
document.write(value + " ");
if (value % 2 == 0)
return true;
else
return false;
}
// Create an array.
var numbers = [2, 4, 5, 6, 8];
// Check whether the callback function returns true for all of the
// array values.
if (numbers.every(CheckIfEven))
document.write("All are even.");
else
document.write("Some are not even.");
// Output:
// 2 4 5 Some are not even.
```

View File

@ -0,0 +1,32 @@
---
title: Array.prototype.fill
---
## Array.prototype.fill
The fill() method fills all the elements in an array with a static value.
Syntax:
``` javascript
arr.fill(value)
arr.fill(value, start)
arr.fill(value, start, end)
```
The fill method takes up to three arguments value, start and end. The start and end arguments are optional with default values of 0 and the length of the this object.
The fill method is a mutable method, it will change this object itself, and return it, not just return a copy of it.
## Examples
```javascript
[1, 2, 3].fill(4); // [4, 4, 4]
[1, 2, 3].fill(4, 1); // [1, 4, 4]
var fruits = ["Grape", "Pear", "Apple", "Strawberry"];
fruits.fill("Watermelon", 2, 4); // Banana, Pear, Watermelon, Watermelon
```
#### More Information:
For more information visit [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill)

View File

@ -0,0 +1,74 @@
---
title: Array.prototype.filter
---
## Array.prototype.filter
The filter method takes an array as an input. It takes each element in the array and it applies a conditional statement against it. If this conditional returns true, the element gets "pushed" to the output array.
Once each element in the input array is "filtered" as such, it outputs a new array containing each element that returned true.
In this example below, there is an array that has multiple objects within it. Normally, to iterate through this array, you might use a for loop.
In this case, we want to get all the students whose grades are greater than or equal to 90.
```javascript
var students = [
{ name: 'Quincy', grade: 96 },
{ name: 'Jason', grade: 84 },
{ name: 'Alexis', grade: 100 },
{ name: 'Sam', grade: 65 },
{ name: 'Katie', grade: 90 }
];
//Define an array to push student objects to.
var studentsGrades = []
for (var i = 0; i < students.length; i++) {
//Check if grade is greater than 90
if (students[i].grade >= 90) {
//Add a student to the studentsGrades array.
studentsGrades.push(students[i])
}
}
return studentsGrades; // [ { name: 'Quincy', grade: 96 }, { name: 'Alexis', grade: 100 }, { name: 'Katie', grade: 90 } ]
```
This for loop works, but it is pretty lengthy. It can also become tedious to write for loops over and over again for many arrays that you need to iterate through.
This is a great use case for filter!
Here is the same example using filter:
```javascript
var students = [
{ name: 'Quincy', grade: 96 },
{ name: 'Jason', grade: 84 },
{ name: 'Alexis', grade: 100 },
{ name: 'Sam', grade: 65 },
{ name: 'Katie', grade: 90 }
];
var studentGrades = students.filter(function (student) {
//This tests if student.grade is greater than or equal to 90. It returns the "student" object if this conditional is met.
return student.grade >= 90;
});
return studentGrades; // [ { name: 'Quincy', grade: 96 }, { name: 'Alexis', grade: 100 }, { name: 'Katie', grade: 90 } ]
```
The filter method is much faster to write and cleaner to read while still accomplishing the same thing. Using ES6 syntax we can even replicate the 6-line for-loop with filter:
```javascript
var students = [
{ name: 'Quincy', grade: 96 },
{ name: 'Jason', grade: 84 },
{ name: 'Alexis', grade: 100 },
{ name: 'Sam', grade: 65 },
{ name: 'Katie', grade: 90 }
];
var studentGrades = students.filter(student => student.grade >= 90);
return studentGrades; // [ { name: 'Quincy', grade: 96 }, { name: 'Alexis', grade: 100 }, { name: 'Katie', grade: 90 } ]
```
Filter is very useful and a great choice over for loops to filter arrays against conditional statements.
#### More Information:
<a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter' target='_blank' rel='nofollow'>MDN</a>

View File

@ -0,0 +1,67 @@
---
title: Array.prototype.find
---
## Information
The `find()` method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned. The `find()` method does not mutate the array on which it is called.
Syntax:
```
arr.find(callback[, thisArg])
```
##### Parameters
- `callback`
- Function to execute on each value in the array, taking three arguments:
- `element`
- The current element being processed in the array.
- `index`
- The index of the current element being processed in the array.
- `array`
- The array find was called upon.
- `thisArg` (Optional)
- Object to use as this when executing callback.
##### Return value
A value in the array if an element passes the test; otherwise, undefined.
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)
## Examples
This example will find the corresponding item in the array and return the object from it.
```javascript
let items = [
{name: 'books', quantity: 2},
{name: 'movies', quantity: 1},
{name: 'games', quantity: 5}
];
function findMovies(item) {
return item.name === 'movies';
}
console.log(items.find(findMovies));
// Output
// { name: 'movies', quantity: 1 }
```
The following example shows the output of each optional parameter to the callback function. This will return `undefined` because none of the items will return true from the callback function.
```javascript
function showInfo(element, index, array) {
console.log('element = ' + element + ', index = ' + index + ', array = ' + array);
return false;
}
console.log('return = ' + [4, 6, 8, 12].find(showInfo));
// Output
// element = 4, index = 0, array = 4,6,8,12
// element = 6, index = 1, array = 4,6,8,12
// element = 8, index = 2, array = 4,6,8,12
// element = 12, index = 3, array = 4,6,8,12
// return = undefined
```

View File

@ -0,0 +1,70 @@
---
title: Array.prototype.findIndex
---
## Information
The `findIndex()` method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.
The `findIndex()` method does not mutate the array on which it is called.
Syntax:
```
arr.findIndex(callback[, thisArg])
```
##### Parameters
- `callback`
- Function to execute on each value in the array, taking three arguments:
- `element`
- The current element being processed in the array.
- `index`
- The index of the current element being processed in the array.
- `array`
- The array findIndex() was called upon.
- `thisArg` (Optional)
- Object to use as this when executing callback.
##### Return value
A index in the array if an element passes the test; otherwise, -1.
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex)
## Examples
This example will find the corresponding item in the array and return the index from it.
```javascript
let items = [
{name: 'books', quantity: 2},
{name: 'movies', quantity: 1},
{name: 'games', quantity: 5}
];
function findMovies(item) {
return item.name === 'movies';
}
console.log(items.findIndex(findMovies));
// Index of 2nd element in the Array is returned,
// so this will result in '1'
```
The following example shows the output of each optional parameter to the callback function. This will return `-1` because none of the items will return true from the callback function.
```javascript
function showInfo(element, index, array) {
console.log('element = ' + element + ', index = ' + index + ', array = ' + array);
return false;
}
console.log('return = ' + [4, 6, 8, 12].findIndex(showInfo));
// Output
// element = 4, index = 0, array = 4,6,8,12
// element = 6, index = 1, array = 4,6,8,12
// element = 8, index = 2, array = 4,6,8,12
// element = 12, index = 3, array = 4,6,8,12
// return = -1
```

View File

@ -0,0 +1,35 @@
---
title: Array.prototype.forEach
---
## Array.prototype.forEach
The 'forEach' array method is used to iterate through each item in an array. The method is called on the array Object and is passed a function that is called on each item in the array.
```javascript
var arr = [1, 2, 3, 4, 5];
arr.forEach(number => console.log(number * 2));
// 2
// 4
// 6
// 8
// 10
```
The callback function can also take a second parameter of an index in case you need to reference the index of the current item in the array.
```javascript
var arr = [1, 2, 3, 4, 5];
arr.forEach((number, i) => console.log(`${number} is at index ${i}`));
// '1 is at index 0'
// '2 is at index 1'
// '3 is at index 2'
// '4 is at index 3'
// '5 is at index 4'
```
#### More Information:
<a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach' target='_blank' rel='nofollow'>MDN Article on Array.prototype.forEach()</a>

View File

@ -0,0 +1,23 @@
---
title: Array.prototype.includes
---
## Array.prototype.includes
The `includes()` method determines whether an array includes a value. It returns true or false.
It takes two arguments:
1. `searchValue` - The element to search for in the array.
2. `fromIndex` - The position in the array to start searching for the proivded `searchValue`. If a negative value is supplied it starts from the array's length minus the negative value.
### Example
```js
const a = [1, 2, 3];
a.includes(2); // true
a.includes(4); // false
```
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes)

View File

@ -0,0 +1,41 @@
---
title: Array.prototype.indexOf
---
## Array.prototype.indexOf
The `indexOf()` method returns the first index at which a given element can be found in the array. If the element is not present, it returns -1.
**Syntax**
```javascript
arr.indexOf(searchElement[, fromIndex])
```
## Parameters
* **searchElement** Element for which you are looking
* **fromIndex** Optional. The index at which you want to start the search at. Ifthe fromIndex is greater than or equal to the array's length, the array is not searched and the method returns -1. If the fromIndex is a negative number, it considered an offset from the end of the array (the array is still searched forwards from there). The default value is 0, which means the entire array is searched.
## Description
The `indexOf` method takes each array element in ascending index order and checks it against `searchElement` using strict equality (`===`). Once it finds an element that returns `true`, it returns its index.
## Examples
```javascript
var array = [1, 2, 4, 1, 7]
array.indexOf(1); // 0
array.indexOf(7); // 4
array.indexOf(6); // -1
array.indexOf('1'); // -1
array.indexOf('hello'); // -1
array.indexOf(1, 2); // 3
array.indexOf(1, -3); // 3
```
### More Information:
<a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf' target='_blank' rel='nofollow'>MDN link</a>
<a href='https://docs.microsoft.com/en-us/scripting/javascript/reference/indexof-method-array-javascript' target='_blank' rel='nofollow'>MSDN Link</a>

View File

@ -0,0 +1,36 @@
---
title: Array.prototype.join
---
The JavaScript array method `.join()` will combine all elements of an array into a single string.
**Syntax**
```javascript
var array = ["Lorem", "Ipsum", "Dolor", "Sit"];
var str = array.join([separator]);
```
## Parameters
**separator**
Optional. Specifies the string to use to separate each element of the original array. If the separator is not a string, it will be converted to a string. If separator parameter is not provided, array elements are separated with a comma by default. If separator is an empty string `""`, all array elements are joined without a separator character between them.
## Description
`.join()` joins all elements of an array into a single string. If any of the array elements are `undefined` or `null`, that element is converted to the empty string `""`.
## Examples
**Using `.join()` four different ways**
```javascript
var array = ["Lorem", "Ipsum", "Dolor" ,"Sit"];
var join1 = array.join(); /* assigns "Lorem,Ipsum,Dolor,Sit" to join1 variable
(because no separator was provided .join()
defaulted to using a comma) */
var join2 = array.join(", "); // assigns "Lorem, Ipsum, Dolor, Sit" to join2 variable
var join3 = array.join(" + "); // assigns "Lorem + Ipsum + Dolor + Sit" to join3 variable
var join4 = array.join(""); // assigns "LoremIpsumDolorSit" to join4 variable
```
Source : <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join' target='_blank' rel='nofollow'>MDN</a>

View File

@ -0,0 +1,71 @@
---
title: Array.prototype.lastIndexOf
---
## Array.prototype.lastIndexof
The `lastIndexOf()` method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at `fromIndex`.
**Syntax**
```javascript
arr.lastIndexOf(searchElement, fromIndex = arr.length - 1])
```
## Parameters
* **searchElement**
* Element to locate in the array.
* **fromIndex**
* _Optional_. The index at which to start searching backwards. Defaults to the array's length minus one, i.e. the whole array will be searched. If the index is greater than or equal to the length of the array, the whole array will be searched. If negative, it is taken as the offset from the end of the array. Note that even when the index is negative, the array is still searched from back to front. If the calculated index is less than 0, -1 is returned, i.e. the array will not be searched.
<a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf' target='_blank' rel='nofollow'>MDN link</a> | <a href='https://msdn.microsoft.com/en-us/LIBRary/ff679972%28v=vs.94%29.aspx' target='_blank' rel='nofollow'>MSDN link</a>
## Returns
The index of the last occurrence of `searchElement` in the array, or -1 if `searchElement` is not found.
## Description
`lastIndexOf` compares `searchElement` to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).
## Remarks
The search occurs in descending index order (last member first). To search in ascending order, use the `indexOf` method.
The optional `fromIndex` argument specifies the array index at which to begin the search. If `fromIndex` is greater than or equal to the array length, the whole array is searched. If `fromIndex` is negative, the search starts at the array length plus `fromIndex`. If the computed index is less than 0, -1 is returned.
## Examples
```javascript
var array = [2, 5, 9, 2];
array.lastIndexOf(2); // 3
array.lastIndexOf(7); // -1
array.lastIndexOf(2, 3); // 3
array.lastIndexOf(2, 2); // 0
array.lastIndexOf(2, -2); // 0
array.lastIndexOf(2, -1); // 3
// Create an array.
var ar = ["ab", "cd", "ef", "ab", "cd"];
// Determine the first location, in descending order, of "cd".
document.write(ar.lastIndexOf("cd") + "<br/>");
// Output: 4
// Find "cd" in descending order, starting at index 2.
document.write(ar.lastIndexOf("cd", 2) + "<br/>");
// Output: 1
// Search for "gh" (which is not found).
document.write(ar.lastIndexOf("gh")+ "<br/>");
// Output: -1
// Find "ab" with a fromIndex argument of -3.
// The search in descending order starts at index 3,
// which is the array length minus 2.
document.write(ar.lastIndexOf("ab", -3) + "<br/>");
// Output: 0
```

Some files were not shown because too many files have changed in this diff Show More