Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Common JavaScript Gotchas
Akshay Joshi
Akshay Joshi

Posted on

     

Common JavaScript Gotchas

  1. Global Variables:
    • Problem: Forgetting to usevar,let, orconst can create global variables unintentionally.
    • Solution: Always declare variables withlet orconst.
// Badx=10;// Goodletx=10;
Enter fullscreen modeExit fullscreen mode
  1. Variable Hoisting:
    • Problem: Variables declared withvar are hoisted to the top of their scope, which can lead to unexpected behavior.
    • Solution: Uselet andconst to avoid hoisting issues.
console.log(x);// undefinedvarx=5;// Use let or constconsole.log(y);// ReferenceError: y is not definedlety=5;
Enter fullscreen modeExit fullscreen mode
  1. Function Hoisting:
    • Problem: Function declarations are hoisted, but function expressions are not.
// This worksgreet();functiongreet(){console.log('Hello');}// This does not worksayHi();// TypeError: sayHi is not a functionvarsayHi=function(){console.log('Hi');};
Enter fullscreen modeExit fullscreen mode
  1. this Keyword:
    • Problem: The value ofthis can change depending on the context in which a function is called.
    • Solution: Use arrow functions or.bind() to maintain the correctthis context.
functionPerson(name){this.name=name;setTimeout(function(){console.log(this.name);// undefined},1000);}// Using arrow functionfunctionPerson(name){this.name=name;setTimeout(()=>{console.log(this.name);// Correctly logs the name},1000);}
Enter fullscreen modeExit fullscreen mode
  1. Equality Operators:
    • Problem: The== operator performs type coercion, which can lead to unexpected results.
    • Solution: Use the=== operator for strict equality checks.
console.log(0=='0');// trueconsole.log(0==='0');// false
Enter fullscreen modeExit fullscreen mode
  1. Falsy Values:
    • Problem: Understanding what values are considered falsy (false,0,'',null,undefined,NaN).
    • Solution: Be mindful when checking for truthy or falsy values.
if(0){console.log('This will not run');}
Enter fullscreen modeExit fullscreen mode
  1. Closure Scope:
    • Problem: Loop variables in closures can lead to unexpected behavior.
    • Solution: Uselet in loops to ensure block scope.
for(vari=1;i<=3;i++){setTimeout(function(){console.log(i);// Logs 4, 4, 4},i*1000);}// Using letfor(leti=1;i<=3;i++){setTimeout(function(){console.log(i);// Logs 1, 2, 3},i*1000);}
Enter fullscreen modeExit fullscreen mode
  1. Default Parameters:
    • Problem: Older JavaScript versions don't support default parameters.
    • Solution: Use ES6 default parameters or logical operators.
functiongreet(name){name=name||'Guest';console.log('Hello'+name);}// ES6 Default parametersfunctiongreet(name='Guest'){console.log(`Hello${name}`);}
Enter fullscreen modeExit fullscreen mode
  1. Array Methods:
    • Problem: Confusingmap,forEach,filter,reduce.
    • Solution: Understand the purpose and return values of each method.
constnumbers=[1,2,3,4];numbers.forEach(n=>console.log(n));// Logs each numberconstdoubled=numbers.map(n=>n*2);// Returns [2, 4, 6, 8]constevens=numbers.filter(n=>n%2===0);// Returns [2, 4]constsum=numbers.reduce((total,n)=>total+n,0);// Returns 10
Enter fullscreen modeExit fullscreen mode
  1. Async/Await:

    • Problem: Misunderstanding how to handle asynchronous code.
    • Solution: Useasync andawait for cleaner asynchronous code.
    asyncfunctionfetchData(){try{constresponse=awaitfetch('https://api.example.com/data');constdata=awaitresponse.json();console.log(data);}catch(error){console.error('Error fetching data',error);}}

Understanding these common pitfalls can help you write more robust and maintainable JavaScript code. If you have any specific scenarios or examples you'd like to delve into, feel free to ask!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Goa-born IT grad in Bangalore, quirky tech co-founder of DoozieSoft (2013). Embraces hakuna matata, believes money follows effort. Devoted dad of two, balancing code and family life. Memento vivere.
  • Location
    Bangalore, India
  • Education
    Goa College of Engineering
  • Pronouns
    he/him
  • Work
    CTO at Doozie Software Solutions
  • Joined

More fromAkshay Joshi

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp