Can global constants be declared in JavaScript?

前端 未结 8 842
耶瑟儿~
耶瑟儿~ 2020-12-16 09:33

If so, what is the syntax for such a declaration?

8条回答
  •  爱一瞬间的悲伤
    2020-12-16 09:46

    For the record.

    // ES6+ code:
    const CONSTGLOBAL1=200;  // it is a constant global
    
    function somef() { 
       document.write(CONSTGLOBAL1); // CONSTGLOBAL1 is defined (because it's global)
       const CONSTLOCAL=200; // it's a local constant
       document.write(CONSTLOCAL); // CONSTLOCAL is defined
    }       
    somef();
    document.write(CONSTLOCAL); // CONSTLOCALis NOT defined.
    

    So, if the constant is defined inside {} then it's local, otherwise, it's global.

提交回复
热议问题