Quiz
- I would like to talk more about the .keys() function.
Glad to. It's similar to the Python method of the same name:
dic.keys()returns a sequence of the keys in the given dictionary. The equivalent in JS isObject.keys(dic)which is a method on a global variable calledObject. It also returns a list of the keys. Here's an example:In practice, as in Python, we would typically use that information to iterate over the object and do stuff with it, say, print it out:
- Is there a relationship between namespaces and closures? since closures keep variables in their own scope
Yes! The "inside" or "execution context" of a function creates a new namespace, extending the global or existing namespace.
Closure variables are non-local, non-global names in those inner namespaces.
Modules are all about global names.
- Can you only import something to a file if its origin file explicitly exports it?
Yes, that's right. The module has to explicitly export the name.
This is different from Python, where you can get access to everything, even if maybe you shouldn't.
Reasonable people could disagree on which is better: Is Python too trusting? Is JS too suspicious?
But, those are the (different) rules of the game.
- Can you talk more about globalThis? Why can console access the javascript file we used in plotting assignment but not modules?
You can read more than you ever wanted to know about globalThis.
The key idea is that it was introduced to create a standard way of accessing the global environment/namespace.
It's useful to us because it allows code in a module to set global variables that aren't restricted that module.
Honestly,
globalThisis a violation of the separation that modules are intended for. It's a loophole. Use it sparingly and thoughtfully.I would really only use it for debugging. For production code, I would stick to defined interfaces.
- I am a little bit confused by strict mode.
It patches what many people think was a mistake in the overly permissive early versions of JS.
Consider the assignment statement inside the function
foo:Which of the following is it?
- Is that setting a new global variable called
asn? - Is it a typo, where the programmer intended to set the existing global variable
ans?
Option 1 is the original JS. Option 2 is strict mode.
- Is that setting a new global variable called
- Currently no, thanks!
Great!