3

reading the code I found out code like this

window["foo"]=
   function() {
      alert("foo");
   }

And if I call the function for example on onclick("foo()") I will get "foo" So what is window["foo"] ?

4
  • 5
    It's...the foo property on window. JavaScript property access: dot notation vs. brackets? Commented May 14, 2021 at 14:58
  • 2
    Basically it is creating property named "foo" under window object (that is always present), and assigns function to this property. Same will be window.foo = function... Commented May 14, 2021 at 14:58
  • 2
    window is an object. window["foo"] is equivalent to window.foo Commented May 14, 2021 at 15:11
  • 2
    side note.... don't do that Commented May 14, 2021 at 15:23

2 Answers 2

4

foo is function declared as a prop in the window object which is the top level scope . which means your variable is accessed globaly from any place in you code , and its accessible like this :

window["foo"]=
   function() {
      alert("foo");
   }


window["foo"]();
window.foo();
foo(); // this is your attempt on onclick

Sign up to request clarification or add additional context in comments.

Comments

4

Foo Word:

Foo (pronounced FOO) is a term used by programmers as a placeholder for a value that can change, depending on conditions or on information passed to the program.

So, "Foo" is just a popular word among programmers like "Hello World" for the first program to learn code.

The explanation for your code:

Your code creates a string property under the window object called "Foo" and assigns a function to this property which is the alert function so when JavaScript listens to a property called Foo (e.g the onclick function), it will call the alert function which you will see alert called "Foo".

An example for JavaScript Objects & Properties:

// JavaScript Object & Properties
// there are two different ways to access an object property
// you can use .property or ["property"].


var person = {
  firstname:"John",
  lastname:"Doe",
  age:50,
  eyecolor:"blue"
};

console.log(person["firstname"] + " is " + person["age"] + " years old.");

Documentation for Javascript Objects & Properties

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.