SlideShare uma empresa Scribd logo
1 de 19
Baixar para ler offline
Powerful JavaScript TipsPowerful JavaScript Tips
Techniques that all JavaScript programmers can use now
you needn’t be an advanced JavaScript developer to benefit from these tips
Powerful JavaScript TipsPowerful JavaScript Tips
1. “short circuting” method
To set default values, instead of this:
function fileName(name)
​ if (!name) {
name = "unknown_name";
}
return name;
}
Use this:
function fileName(name)
name = name || "unknown_name";
return name;
}
Powerful JavaScript TipsPowerful JavaScript Tips
2. “short circuting” with && (AND)
Instead of this:
function isAdult(age) {
if (age && age > 17) {
return true;
}
​else {
return false;
}
}
Use this:
function isAdult(age) {
return age && age > 17 ;
}
Powerful JavaScript TipsPowerful JavaScript Tips
3. It gets more exciting!
Instead of this:
if (userName) {
logIn(userName);
}
else {
signUp();
}
Use this:
userName && logIn (userName) || signUp ();
Powerful JavaScript TipsPowerful JavaScript Tips
4. powerful uses of immediately invoked function expressions
Immediately and after invoke
(showName = function (name) {
console.log(name || "No Name")
}) (); // No Name​
​
showName ("Mike"); // Mike
Powerful JavaScript TipsPowerful JavaScript Tips
5. when to use immediately invoked function expressions?
All the code is wrapped in the IIFE​
(function () {
​var firstName = “Dragos”, concatenated = undefined;
function init () {
doStuff (firstName);
// code to start the application​
}
​
​function doStuff (firstName) {
concatenated = firstName + 'Developer';
doMoreStuff();
}
​
​function doMoreStuff () {
console.log('Concatenated = ', concatenated;
}
​
​// Start the application
init ();
}) ();
BONUSJavaScript Best Practices
JavaScript Best Practices
1 – Don’t forget var keyword when assigning a variable’s value for the first time.
JavaScript Best Practices
1 – Don’t forget var keyword when assigning a variable’s value for the first time.
2 – use === instead of ==
JavaScript Best Practices
1 – Don’t forget var keyword when assigning a variable’s value for the first time.
2 – use === instead of ==
3 – undefined, null, 0, false, NaN, '' (empty string) are all falsy.
JavaScript Best Practices
1 – Don’t forget var keyword when assigning a variable’s value for the first time.
2 – use === instead of ==
3 – undefined, null, 0, false, NaN, '' (empty string) are all falsy.
4 – Be careful when using typeof, instanceof and constructor.
typeof : a JavaScript unary operator used to return a string that represents the primitive
type of a variable, don’t forget that typeof null will return “object”,
and for the majority of object types (Array, Date, and others) will return also “object”.
constructor : is a property of the internal prototype property, which
could be overridden by code.
instanceof : is another JavaScript operator that check in all the prototypes chain the
constructor it returns true if it’s found and false if not.
JavaScript Best Practices
1 – Don’t forget var keyword when assigning a variable’s value for the first time.
2 – use === instead of ==
3 – undefined, null, 0, false, NaN, '' (empty string) are all falsy.
4 – Be careful when using typeof, instanceof and constructor.
typeof : a JavaScript unary operator used to return a string that represents the primitive
type of a variable, don’t forget that typeof null will return “object”,
and for the majority of object types (Array, Date, and others) will return also “object”.
constructor : is a property of the internal prototype property, which
could be overridden by code.
instanceof : is another JavaScript operator that check in all the prototypes chain the
constructor it returns true if it’s found and false if not.
5 – Get a random item from an array
3 – undefined, null, 0, false, NaN, '' (empty string) are all falsy.
var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];
var randomItem = items[Math.floor(Math.random() * items.length)];
JavaScript Best Practices
1 – Don’t forget var keyword when assigning a variable’s value for the first time.
2 – use === instead of ==
3 – undefined, null, 0, false, NaN, '' (empty string) are all falsy.
4 – Be careful when using typeof, instanceof and constructor.
typeof : a JavaScript unary operator used to return a string that represents the primitive
type of a variable, don’t forget that typeof null will return “object”,
and for the majority of object types (Array, Date, and others) will return also “object”.
constructor : is a property of the internal prototype property, which
could be overridden by code.
instanceof : is another JavaScript operator that check in all the prototypes chain the
constructor it returns true if it’s found and false if not.
5 – Get a random item from an array
3 – undefined, null, 0, false, NaN, '' (empty string) are all falsy.
var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];
var randomItem = items[Math.floor(Math.random() * items.length)];
6 – Generate an array of numbers with numbers from 0 to max
var numbersArray = [] , max = 100;
for( var i=1; numbersArray.push(i++) < max;); // numbers = [1,2,3 ... 100]
JavaScript Best Practices
7 – Append an array to another array
var array1 = [12 , "foo" , {name "Joe"} , -2458];
var array2 = ["Doe" , 555 , 100];
Array.prototype.push.apply(array1, array2);
/* array1 will be equal to [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */
JavaScript Best Practices
7 – Append an array to another array`
var array1 = [12 , "foo" , {name "Joe"} , -2458];
var array2 = ["Doe" , 555 , 100];
Array.prototype.push.apply(array1, array2);
/* array1 will be equal to [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */
8 – Transform the arguments object into an array
var argArray = Array.prototype.slice.call(arguments);
JavaScript Best Practices
7 – Append an array to another array`
var array1 = [12 , "foo" , {name "Joe"} , -2458];
var array2 = ["Doe" , 555 , 100];
Array.prototype.push.apply(array1, array2);
/* array1 will be equal to [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */
8 – Transform the arguments object into an array
var argArray = Array.prototype.slice.call(arguments);
9 – Verify that a given argument is a number
function isNumber(n){
return !isNaN(parseFloat(n)) && isFinite(n);
}
JavaScript Best Practices
7 – Append an array to another array`
var array1 = [12 , "foo" , {name "Joe"} , -2458];
var array2 = ["Doe" , 555 , 100];
Array.prototype.push.apply(array1, array2);
/* array1 will be equal to [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */
8 – Transform the arguments object into an array
var argArray = Array.prototype.slice.call(arguments);
9 – Verify that a given argument is a number
function isNumber(n){
return !isNaN(parseFloat(n)) && isFinite(n);
}
10 – Verify that a given argument is an array
function isArray(obj){
return Object.prototype.toString.call(obj) === '[object Array]' ;
}
JavaScript Best Practices
7 – Append an array to another array
var array1 = [12 , "foo" , {name "Joe"} , -2458];
var array2 = ["Doe" , 555 , 100];
Array.prototype.push.apply(array1, array2);
/* array1 will be equal to [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */
8 – Transform the arguments object into an array
var argArray = Array.prototype.slice.call(arguments);
9 – Verify that a given argument is a number
function isNumber(n){
return !isNaN(parseFloat(n)) && isFinite(n);
}
10 – Verify that a given argument is an array
function isArray(obj){
return Object.prototype.toString.call(obj) === '[object Array]' ;
}
11 – Don’t use delete to remove an item from array
Use splice instead of using delete to delete an item from an array. Using delete replaces
the item with undefined instead of the removing it from the array.
Dragos Ionita
Software Engineer
https://ro.linkedin.com/in/dragos-ionita-8ab20756
Dragos Ionita
Software Engineer
https://ro.linkedin.com/in/dragos-ionita-8ab20756
Thanks for watching!Thanks for watching!

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Bottom Up
Bottom UpBottom Up
Bottom Up
 
Headless Js Testing
Headless Js TestingHeadless Js Testing
Headless Js Testing
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best Practices
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Anonymous functions in JavaScript
Anonymous functions in JavaScriptAnonymous functions in JavaScript
Anonymous functions in JavaScript
 
JavaScript Design Patterns
JavaScript Design PatternsJavaScript Design Patterns
JavaScript Design Patterns
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
 

Destaque

Grow Smart Program Outline
Grow Smart Program OutlineGrow Smart Program Outline
Grow Smart Program Outline
Ervin Gruia
 

Destaque (17)

Web Application Development Tools for Creating Perfect User Experience
Web Application Development Tools for Creating Perfect User ExperienceWeb Application Development Tools for Creating Perfect User Experience
Web Application Development Tools for Creating Perfect User Experience
 
vExpert 2014 Certificate by Nathan Gusti Ryan
vExpert 2014 Certificate by Nathan Gusti RyanvExpert 2014 Certificate by Nathan Gusti Ryan
vExpert 2014 Certificate by Nathan Gusti Ryan
 
Cross Functional Alignment Around the Customer Processes to Drive Success
Cross Functional Alignment Around the Customer Processes to Drive SuccessCross Functional Alignment Around the Customer Processes to Drive Success
Cross Functional Alignment Around the Customer Processes to Drive Success
 
vExpert 2015 Certificate by Nathan Gusti Ryan
vExpert 2015 Certificate by Nathan Gusti RyanvExpert 2015 Certificate by Nathan Gusti Ryan
vExpert 2015 Certificate by Nathan Gusti Ryan
 
Jose celi
Jose celiJose celi
Jose celi
 
Grow Smart Program Outline
Grow Smart Program OutlineGrow Smart Program Outline
Grow Smart Program Outline
 
Thames valley prevention powerpoint n.1 v2
Thames valley prevention powerpoint n.1 v2Thames valley prevention powerpoint n.1 v2
Thames valley prevention powerpoint n.1 v2
 
Creative designer and front end developer - Two faces of the same coin
Creative designer and front end developer - Two faces of the same coinCreative designer and front end developer - Two faces of the same coin
Creative designer and front end developer - Two faces of the same coin
 
Ben Brauneck
Ben BrauneckBen Brauneck
Ben Brauneck
 
El carnestoltes
El carnestoltesEl carnestoltes
El carnestoltes
 
Del dicho al hecho: analizando proyectos
Del dicho al hecho: analizando proyectosDel dicho al hecho: analizando proyectos
Del dicho al hecho: analizando proyectos
 
Socrative - Gamification in education - Manu Melwin Joy
Socrative - Gamification in education - Manu Melwin JoySocrative - Gamification in education - Manu Melwin Joy
Socrative - Gamification in education - Manu Melwin Joy
 
Tooling for the productive front-end developer
Tooling for the productive front-end developerTooling for the productive front-end developer
Tooling for the productive front-end developer
 
Globalizacion en Ecuador by Diana
Globalizacion en Ecuador by DianaGlobalizacion en Ecuador by Diana
Globalizacion en Ecuador by Diana
 
Google Chrome developer tools
Google Chrome developer toolsGoogle Chrome developer tools
Google Chrome developer tools
 
Smart Sales: entendiendo el proceso de venta
Smart Sales: entendiendo el proceso de ventaSmart Sales: entendiendo el proceso de venta
Smart Sales: entendiendo el proceso de venta
 
Por qué unirse a la comunidad global de WordPress y cómo ser parte del movimi...
Por qué unirse a la comunidad global de WordPress y cómo ser parte del movimi...Por qué unirse a la comunidad global de WordPress y cómo ser parte del movimi...
Por qué unirse a la comunidad global de WordPress y cómo ser parte del movimi...
 

Semelhante a Powerful JavaScript Tips and Best Practices

JavaScript Proven Practises
JavaScript Proven PractisesJavaScript Proven Practises
JavaScript Proven Practises
Robert MacLean
 
An introduction to property-based testing
An introduction to property-based testingAn introduction to property-based testing
An introduction to property-based testing
Vincent Pradeilles
 

Semelhante a Powerful JavaScript Tips and Best Practices (20)

An introduction to javascript
An introduction to javascriptAn introduction to javascript
An introduction to javascript
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
Core concepts-javascript
Core concepts-javascriptCore concepts-javascript
Core concepts-javascript
 
Test driven node.js
Test driven node.jsTest driven node.js
Test driven node.js
 
JavaScript Proven Practises
JavaScript Proven PractisesJavaScript Proven Practises
JavaScript Proven Practises
 
Extending javascript part one
Extending javascript part oneExtending javascript part one
Extending javascript part one
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
 
Enumerable
EnumerableEnumerable
Enumerable
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
 
Functional Javascript
Functional JavascriptFunctional Javascript
Functional Javascript
 
Einführung in TypeScript
Einführung in TypeScriptEinführung in TypeScript
Einführung in TypeScript
 
An introduction to property-based testing
An introduction to property-based testingAn introduction to property-based testing
An introduction to property-based testing
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Java Script Workshop
Java Script WorkshopJava Script Workshop
Java Script Workshop
 
Basics of Javascript
Basics of JavascriptBasics of Javascript
Basics of Javascript
 

Mais de Dragos Ionita

Mais de Dragos Ionita (7)

Reactive programming - Observable
Reactive programming - ObservableReactive programming - Observable
Reactive programming - Observable
 
Adventures with Angular 2
Adventures with Angular 2Adventures with Angular 2
Adventures with Angular 2
 
The new way to write a frontend software
The new way to write a frontend softwareThe new way to write a frontend software
The new way to write a frontend software
 
Robotics and Arduino (Arduino UNO)
Robotics and Arduino (Arduino UNO)Robotics and Arduino (Arduino UNO)
Robotics and Arduino (Arduino UNO)
 
Html5 - Awesome APIs
Html5 - Awesome APIsHtml5 - Awesome APIs
Html5 - Awesome APIs
 
Hybrid Mobile Application with Ionic Framework
Hybrid Mobile Application with Ionic FrameworkHybrid Mobile Application with Ionic Framework
Hybrid Mobile Application with Ionic Framework
 
Google Tag Manager (GTM)
Google Tag Manager (GTM)Google Tag Manager (GTM)
Google Tag Manager (GTM)
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 

Powerful JavaScript Tips and Best Practices

  • 1. Powerful JavaScript TipsPowerful JavaScript Tips Techniques that all JavaScript programmers can use now you needn’t be an advanced JavaScript developer to benefit from these tips
  • 2. Powerful JavaScript TipsPowerful JavaScript Tips 1. “short circuting” method To set default values, instead of this: function fileName(name) ​ if (!name) { name = "unknown_name"; } return name; } Use this: function fileName(name) name = name || "unknown_name"; return name; }
  • 3. Powerful JavaScript TipsPowerful JavaScript Tips 2. “short circuting” with && (AND) Instead of this: function isAdult(age) { if (age && age > 17) { return true; } ​else { return false; } } Use this: function isAdult(age) { return age && age > 17 ; }
  • 4. Powerful JavaScript TipsPowerful JavaScript Tips 3. It gets more exciting! Instead of this: if (userName) { logIn(userName); } else { signUp(); } Use this: userName && logIn (userName) || signUp ();
  • 5. Powerful JavaScript TipsPowerful JavaScript Tips 4. powerful uses of immediately invoked function expressions Immediately and after invoke (showName = function (name) { console.log(name || "No Name") }) (); // No Name​ ​ showName ("Mike"); // Mike
  • 6. Powerful JavaScript TipsPowerful JavaScript Tips 5. when to use immediately invoked function expressions? All the code is wrapped in the IIFE​ (function () { ​var firstName = “Dragos”, concatenated = undefined; function init () { doStuff (firstName); // code to start the application​ } ​ ​function doStuff (firstName) { concatenated = firstName + 'Developer'; doMoreStuff(); } ​ ​function doMoreStuff () { console.log('Concatenated = ', concatenated; } ​ ​// Start the application init (); }) ();
  • 8. JavaScript Best Practices 1 – Don’t forget var keyword when assigning a variable’s value for the first time.
  • 9. JavaScript Best Practices 1 – Don’t forget var keyword when assigning a variable’s value for the first time. 2 – use === instead of ==
  • 10. JavaScript Best Practices 1 – Don’t forget var keyword when assigning a variable’s value for the first time. 2 – use === instead of == 3 – undefined, null, 0, false, NaN, '' (empty string) are all falsy.
  • 11. JavaScript Best Practices 1 – Don’t forget var keyword when assigning a variable’s value for the first time. 2 – use === instead of == 3 – undefined, null, 0, false, NaN, '' (empty string) are all falsy. 4 – Be careful when using typeof, instanceof and constructor. typeof : a JavaScript unary operator used to return a string that represents the primitive type of a variable, don’t forget that typeof null will return “object”, and for the majority of object types (Array, Date, and others) will return also “object”. constructor : is a property of the internal prototype property, which could be overridden by code. instanceof : is another JavaScript operator that check in all the prototypes chain the constructor it returns true if it’s found and false if not.
  • 12. JavaScript Best Practices 1 – Don’t forget var keyword when assigning a variable’s value for the first time. 2 – use === instead of == 3 – undefined, null, 0, false, NaN, '' (empty string) are all falsy. 4 – Be careful when using typeof, instanceof and constructor. typeof : a JavaScript unary operator used to return a string that represents the primitive type of a variable, don’t forget that typeof null will return “object”, and for the majority of object types (Array, Date, and others) will return also “object”. constructor : is a property of the internal prototype property, which could be overridden by code. instanceof : is another JavaScript operator that check in all the prototypes chain the constructor it returns true if it’s found and false if not. 5 – Get a random item from an array 3 – undefined, null, 0, false, NaN, '' (empty string) are all falsy. var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119]; var randomItem = items[Math.floor(Math.random() * items.length)];
  • 13. JavaScript Best Practices 1 – Don’t forget var keyword when assigning a variable’s value for the first time. 2 – use === instead of == 3 – undefined, null, 0, false, NaN, '' (empty string) are all falsy. 4 – Be careful when using typeof, instanceof and constructor. typeof : a JavaScript unary operator used to return a string that represents the primitive type of a variable, don’t forget that typeof null will return “object”, and for the majority of object types (Array, Date, and others) will return also “object”. constructor : is a property of the internal prototype property, which could be overridden by code. instanceof : is another JavaScript operator that check in all the prototypes chain the constructor it returns true if it’s found and false if not. 5 – Get a random item from an array 3 – undefined, null, 0, false, NaN, '' (empty string) are all falsy. var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119]; var randomItem = items[Math.floor(Math.random() * items.length)]; 6 – Generate an array of numbers with numbers from 0 to max var numbersArray = [] , max = 100; for( var i=1; numbersArray.push(i++) < max;); // numbers = [1,2,3 ... 100]
  • 14. JavaScript Best Practices 7 – Append an array to another array var array1 = [12 , "foo" , {name "Joe"} , -2458]; var array2 = ["Doe" , 555 , 100]; Array.prototype.push.apply(array1, array2); /* array1 will be equal to [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */
  • 15. JavaScript Best Practices 7 – Append an array to another array` var array1 = [12 , "foo" , {name "Joe"} , -2458]; var array2 = ["Doe" , 555 , 100]; Array.prototype.push.apply(array1, array2); /* array1 will be equal to [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */ 8 – Transform the arguments object into an array var argArray = Array.prototype.slice.call(arguments);
  • 16. JavaScript Best Practices 7 – Append an array to another array` var array1 = [12 , "foo" , {name "Joe"} , -2458]; var array2 = ["Doe" , 555 , 100]; Array.prototype.push.apply(array1, array2); /* array1 will be equal to [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */ 8 – Transform the arguments object into an array var argArray = Array.prototype.slice.call(arguments); 9 – Verify that a given argument is a number function isNumber(n){ return !isNaN(parseFloat(n)) && isFinite(n); }
  • 17. JavaScript Best Practices 7 – Append an array to another array` var array1 = [12 , "foo" , {name "Joe"} , -2458]; var array2 = ["Doe" , 555 , 100]; Array.prototype.push.apply(array1, array2); /* array1 will be equal to [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */ 8 – Transform the arguments object into an array var argArray = Array.prototype.slice.call(arguments); 9 – Verify that a given argument is a number function isNumber(n){ return !isNaN(parseFloat(n)) && isFinite(n); } 10 – Verify that a given argument is an array function isArray(obj){ return Object.prototype.toString.call(obj) === '[object Array]' ; }
  • 18. JavaScript Best Practices 7 – Append an array to another array var array1 = [12 , "foo" , {name "Joe"} , -2458]; var array2 = ["Doe" , 555 , 100]; Array.prototype.push.apply(array1, array2); /* array1 will be equal to [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */ 8 – Transform the arguments object into an array var argArray = Array.prototype.slice.call(arguments); 9 – Verify that a given argument is a number function isNumber(n){ return !isNaN(parseFloat(n)) && isFinite(n); } 10 – Verify that a given argument is an array function isArray(obj){ return Object.prototype.toString.call(obj) === '[object Array]' ; } 11 – Don’t use delete to remove an item from array Use splice instead of using delete to delete an item from an array. Using delete replaces the item with undefined instead of the removing it from the array.
  • 19. Dragos Ionita Software Engineer https://ro.linkedin.com/in/dragos-ionita-8ab20756 Dragos Ionita Software Engineer https://ro.linkedin.com/in/dragos-ionita-8ab20756 Thanks for watching!Thanks for watching!