Reuben George Thomas
  • NEW!
    NEW!  Connect Ideas Across Notes
    Save time and share insights. With Paragraph Citation, you can quote others’ work with source info built in. If someone cites your note, you’ll see a card showing where it’s used—bringing notes closer together.
    Got it
      • Create new note
      • Create a note from template
        • Sharing URL Link copied
        • /edit
        • View mode
          • Edit mode
          • View mode
          • Book mode
          • Slide mode
          Edit mode View mode Book mode Slide mode
        • Customize slides
        • Note Permission
        • Read
          • Only me
          • Signed-in users
          • Everyone
          Only me Signed-in users Everyone
        • Write
          • Only me
          • Signed-in users
          • Everyone
          Only me Signed-in users Everyone
        • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invite by email
        Invitee

        This note has no invitees

      • Publish Note

        Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

        Your note will be visible on your profile and discoverable by anyone.
        Your note is now live.
        This note is visible on your profile and discoverable online.
        Everyone on the web can find and read all notes of this public team.

        Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

        Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

        Explore these features while you wait
        Complete general settings
        Bookmark and like published notes
        Write a few more notes
        Complete general settings
        Write a few more notes
        See published notes
        Unpublish note
        Please check the box to agree to the Community Guidelines.
        View profile
      • Commenting
        Permission
        Disabled Forbidden Owners Signed-in users Everyone
      • Enable
      • Permission
        • Forbidden
        • Owners
        • Signed-in users
        • Everyone
      • Suggest edit
        Permission
        Disabled Forbidden Owners Signed-in users Everyone
      • Enable
      • Permission
        • Forbidden
        • Owners
        • Signed-in users
      • Emoji Reply
      • Enable
      • Versions and GitHub Sync
      • Note settings
      • Note Insights New
      • Engagement control
      • Make a copy
      • Transfer ownership
      • Delete this note
      • Save as template
      • Insert from template
      • Import from
        • Dropbox
        • Google Drive
        • Gist
        • Clipboard
      • Export to
        • Dropbox
        • Google Drive
        • Gist
      • Download
        • Markdown
        • HTML
        • Raw HTML
    Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
    Create Create new note Create a note from template
    Menu
    Options
    Engagement control Make a copy Transfer ownership Delete this note
    Import from
    Dropbox Google Drive Gist Clipboard
    Export to
    Dropbox Google Drive Gist
    Download
    Markdown HTML Raw HTML
    Back
    Sharing URL Link copied
    /edit
    View mode
    • Edit mode
    • View mode
    • Book mode
    • Slide mode
    Edit mode View mode Book mode Slide mode
    Customize slides
    Note Permission
    Read
    Only me
    • Only me
    • Signed-in users
    • Everyone
    Only me Signed-in users Everyone
    Write
    Only me
    • Only me
    • Signed-in users
    • Everyone
    Only me Signed-in users Everyone
    Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- slideOptions: spotlight: enabled: true fragments: true --- <style> .reveal { font-size: 28px; } </style> # Javascript gotchas --- - before we start: - this talk is going to have lots of examples, which I'll type in a repl.it as we go, to save time. but feel free to try them out afterwards. - there's a lot of info, but i've tried to make it all digestible. some of you may already be familiar with some of these topics, the point is that hopefully there's a takeaway for everyone. - this method will come in handy for all your object experiments. ```javascript console.dir() ``` - dissect your objects, don't just get [object Object] printed out. - but what is [object Object]? --- ## let's talk about scope --- - scope is a fancy word describing where your variables exist, and where they can be accessed from within your code. - kind of like roles in a database, you'll want to limit certain variables so they can only be accessed by the bits of code with the right access privileges --- # Levels of scope --- ```javascript //not using var-let-const here because i'll explain those in a sec variableInGlobalScope=2; function cool(){ variableinFunctionScope=3; //this is the simplest form of a block. //usually a block scope occurs in an if statement or a loop though { variableInBlockScope=5 } } ``` - global scope - the outermost level, variables declared here are accessible anywhere. - function scope - functions have their own scope, and variables declared within a function can't be accessed outside it. - block scope - anything grouped by curly brackets. if statements, loops, switch, or you can even create a block just using a pair of brackets by itself. --- ```javascript var variableOutsideFunction = 2 const enteringFunctionScope = () => { var variableInsideFunction = 3 var enteringBlockScope = true if(enteringBlockScope){ var variableInsideBlock = 5 } console.log({variableInsideFunction}) console.log({variableOutsideFunction}) console.log({variableInsideBlock}) } console.log("entering function scope") enteringFunctionScope() console.log("back to global scope") console.log({variableOutsideFunction}) console.log({variableInsideFunction}) ``` - all var! what happens here? let's try it out. --- ### everything works, except trying to access a function scoped variable outside that function. --- ```javascript var variableOutsideFunction = 2 const enteringFunctionScope = () => { var variableInsideFunction = 3 var enteringBlockScope = true if(enteringBlockScope){ let variableInsideBlock = 5 } console.log({variableInsideFunction}) console.log({variableOutsideFunction}) console.log({variableInsideBlock}) } console.log("entering function scope") enteringFunctionScope() console.log("back to global scope") console.log({variableOutsideFunction}) console.log({variableInsideFunction}) ``` - the block scope variable has been changed to a let. - let's see what changes (please dont laugh at this pun) --- ### the variable in a block is no longer accessible outside the block, because let is block scoped. --- ```javascript let variableOutsideFunction = 2 const enteringFunctionScope = () => { let variableInsideFunction = 3 let enteringBlockScope = true if(enteringBlockScope){ let variableInsideBlock = 5 } console.log({variableInsideFunction}) console.log({variableOutsideFunction}) console.log({variableInsideBlock}) } console.log("entering function scope") enteringFunctionScope() console.log("back to global scope") console.log({variableOutsideFunction}) console.log({variableInsideFunction}) ``` - everything is a let - what do you think would happen now? --- ### same as before, because apart from inside a block, let and var behave the same --- ## closures - you will probably get asked what a closure is at some point in your web dev career, and it's one of those things that can be frustratingly difficult to explain under pressure. - I remember this concept with an example of my own. --- ```javascript const bigFunction = () => { let outsideVariable = "abcd" return smallFunction = () => { return outsideVariable; } } ``` - here we have a function bigFunction that returns another function smallFunction. - smallFunction itself accesses and returns a variable which is in bigFunction, but outside smallFunction. --- ```javascript const mySmallFunction=bigFunction(); console.log(mySmallFunction()) ``` - here, we're assigning the result of bigFunction to a new variable. since bigFunction returns a function, this new variable will be a function. - this code translates under the hood to: ```javascript mySmallFunction=smallFunction ``` --- - which would be the same as if we wrote the code below ```javascript const mySmallFunction=() => { return outsideVariable; } console.log(mySmallFunction()) ``` - It would seem that outsideVariable is an undefined variable, since mySmallFunction is in global scope, and outsideVariable is buried inside a function. - this would be the case if smallFunction was copied to mySmallFunction with no memory of where it was declared. --- - But that's where closures come in. - all functions in javascript remember where they were created/declared, and they remember the variables that were in scope when they were declared. - this combination of a function and the variables it has access to, is called a closure. - console.dir(mySmallFunction) and this will become super clear. --- # let's talk about objects --- ## dot notation vs bracket notation ```javascript const fac19={ coursefacilitator:"Gregor", students:"lots of smart people" } const vincentvangregor="coursefacilitator" ``` --- **dot notation** - used for string key names. fac19.coursefacilitator looks for a key with a value of "coursefacilitator" ```javascript console.log(fac19.coursefacilitator) ``` --- **bracket notation** - tries to evaluate the value within brackets. - this means we can use variables with bracket notation - fac19[vincentvangregor] finds the value of vincentvangregor(which is "coursefacilitator") and then looks for a key with that value. - can also be used for string key names directly. ```javascript //these will have the same output console.log(fac19[vincentvangregor]) console.log(fac19["coursefacilitator"]) ``` --- **extra** this bracket notation for variables can also be used in reverse, for assigning key names! ```javascript let coursefacilitator = prompt("what should we call gregor?"); const fac19 = { [coursefacilitator]:"Gregor", students:"lots of smart people" } ``` - whatever nickname the user enters for gregor will be his new nickname, and his key in the object. --- ## destructuring, spread and rest operators. *destructuring* - copies array elements, or object keys. - creates separate individual variables. --- - object destructuring: ```javascript const cookie={chocochip:true,milk:true,flour:"unlikely"} let {chocochip,milk,flour} = cookie ``` - creates three separate variables chocochip, milk and flour, and assigns their values from the matching keys of the object "cookie" ```javascript let {chocochip,..otherStuff}=cookie ``` - ... is the rest operator - copies milk and flour into a new object called otherStuff. - can be accessed using otherStuff.milk --- - array destructuring: ```javascript let [smallNumber,mediumNumber,bigNumber] = [1,50,2000] ``` - creates three separate variables smallNumber, mediumNumber and bigNumber whose values are 1, 50 and 2000 respectively ```javascript let [smallNumber,...otherNumbers] = [1,50,2000] ``` - ... is the rest parameter. it creates a new array called otherNumbers and inserts 50 and 2000 as the elements. - otherNumbers[0] would be 50 --- ## spread operator ```javascript let arrayOfNumbers=[1,2,3,4,5] console.log(Math.max(...arr)) ``` - lets you expand an array into multiple function arguments ```javascript let array1=[1,2,3,4,5] let array2=[6,7,8,9] let newArray = [...arrayOfNumbers,...newArray,10,11,12] console.log(newArray) ``` - also lets you combine arrays (fill a new array with all the elements of another array) --- ## lets talk about this. - as a javascript developer, we probably ask "what is this" everyday, but then there's an actual thing called this, and you're like "well what is this this". - yes, that this. --- - functions inside an object are called "methods" of that object ```javascript const courseFacilitator = { sayHello: function(){ console.log(`Hi i'm Gregor`) }, name:"Gregor" }; ``` - there is a shorthand notation for methods ```javascript const courseFacilitator = {} sayHello(){ console.log(`Hi i'm Gregor`) }, name: "Gregor" }; ``` --- ```javascript const courseFacilitator = {} sayHello(){ console.log(`Hi i'm Gregor`) }, name: "Gregor" }; ``` - we see that sayHello could use the name property, instead of hardcoding gregor, so that for the next cf, only the name property would have to change. - we can use "this" here to refer to the courseFacilitator object --- ```javascript= const courseFacilitator = { sayHello(){ console.log(`Hello i'm ${this.name}`) }, name: "Gregor" }; ``` - one way to think of "this" is that it refers to the object on which the function was called. - in other words, the object on the left hand side of the dot, when you call it like so: ```javascript courseFacilitator.sayHello() ``` - the value of "this" within sayHello would be the object used to call the method, which is courseFacilitator here. - so this.name==courseFacilitator.name --- **here's a slightly different example** ```javascript= function sayHello(){ console.log(`Hello i'm ${this.name}`) } //shorthand notation for sayHello:sayHello //makes a new key of sayHello //with the value being the sayHello function defined above const courseFacilitator={ name: "Gregor", sayHello } const founder = { name: "Dan", sayHello } courseFacilitator.sayHello() founder.sayHello() ``` - for line 17, "this" within sayHello will refer to the courseFacilitator object - for line 18, "this" within sayHello will refer to the founder object - we can see that "this" is figured out at runtime, depending on how the function is called. --- - with this information that "this" is calculated when the function is actually called, and not "bound" permanently, here's yet another example ```javascript= const courseFacilitator = { sayHello(){ console.log(`Hello i'm {this.name}`) }, name: "Gregor" }; let sayHelloCopy=courseFacilitator.sayHello() sayHelloCopy(); ``` - sayHelloCopy returns undefined because it is called in global scope. - the value of "this" will be the global object. - which most likely doesnt have a property of "name" --- - to fix that, we would have to "bind" the value of this for our newly created function. - this means we need to point javascript back to the courseFacilitator object, and tell sayHelloCopy to use that object as the value of "this". ```javascript const courseFacilitator = { sayHello(){ console.log(`Hello i'm {this.name}`) }, name: "Gregor" }; let sayHelloCopy=courseFacilitator.sayHello() //this line copies over the function, but also makes sure that the value of "this" is explicitly set to be the course let boundSayHelloCopy=sayHelloCopy.bind(courseFacilitator) boundSayHelloCopy(); ``` - now the value of "this" for boundSayHelloCopy is courseFacilitator. - there's a lot more to "this", that I can't discuss in such a short time! --- ## Constructors - they're a way to make multiple similar objects. **conventions:** - named with capital letter first. - should be executed only with "new" operator. --- ```javascript function CourseFacilitator(name){ this.name=name this.sayHello(){ console.log(`Hello i'm ${this.name}`) } const gregor = new CourseFacilitator("gregor"); const bobby = new CourseFacilitator("bobby"); console.log(bobby) console.log(gregor) bobby.sayHello() gregor.sayHello() ``` - here the "new" keyword creates an empty object. - the value of "this" will be this empty object - it runs the constructor function to add a property of name to the object, the value coming from the function argument. - it then returns this newly created object - this is what happens when you say new Date(), or new Regexp().. somewhere there is a constructor function that will create a new copy of a date object or a regexp object, and fill it up with certain properties --- ## things i didnt cover, but lead on from here - strict mode - the behaviour of arrow functions with regards to "this" - prototypes, inheritance, classes - this is a talk in itself. --- # final note - A lot of this stuff is quite advanced, and you may not directly use it that much in day to day programming. - however, interviewers like asking the tough questions sometimes :cry: - I'd be happy if half of this got imbibed today. takes time and practice for some of the tougher concepts. - I just wanted to share my approach to this, which is to understand the concept from several sources, and then write my own examples for future reference. - this will save you having to read through wordy mdn explanations. - It's okay to forget, it's okay to google. - Keep going, you're all doing great! 🎉 ---

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully