Skip to content

Instantly share code, notes, and snippets.

@mturnwall
Last active November 7, 2018 19:43
Show Gist options
  • Save mturnwall/143975f564b228e6f5bf to your computer and use it in GitHub Desktop.
Save mturnwall/143975f564b228e6f5bf to your computer and use it in GitHub Desktop.
Coding questions and examples for javascript

Code Questions

Casting

var x = 078 + 1, // 79
	y = 077 + 1; // ?

Hoisting

var foo = 1;
bar();
function bar() {
	if (!foo) {
		var foo = 10;
	}
	alert(foo);
}
// what does the alert display?

Memory Leak

var email;
email.message = document.createElement(“div”);
displayList.appendChild(email.message);

// later
displayList.removeAllChildren();

Truthy

if ('value') {
    console.log('value' == false);
    console.log('value' == true);
}

Object Cloning

// what do the console logs output?
var x = {
        hello: 'world'
    },
    y;
y = x;
y.hello = 'goodbye';
console.log(x.hello);
console.log(y.hello);

Assigning global to var

(function() {
   var a = b = 5;
})();
console.log(b);

Null is object too

typeof foo === 'object'

Coding Exericies

Make this work

duplicate([1,2,3,4,5]); // [1, 2, 3, 4, 5, 5, 4, 3, 2, 1]
arr2.concat(arr2.slice().reverse())

Move array elements around

const arr1 = ['a', 'b', 'c', 'd'];
const arr2 = ['a', 'b', 'c', 'd'];
// Move first item to last index - output should be ['b', 'c', 'd', 'a']
arr1.push(arr1.shift());
// Move last item to first index - output should be ['d', 'a', 'b', 'c']
arr2.unshift(arr2.pop());

Flatten Array

const array =  [[0, 1], [2, 3], [4, 5]];
const flatten = arr => arr.reduce((a, b) => a.concat(b) ,[]);

Find the bug

window.addEventListener('load', function projectPreview() {
    window.removeEventListener('load', projectPreview);
    function getProjectHtml() {
        $.ajax({
            url: 'https://qa.usa.mazda.mirum.agency/handlers/projectnotifications.ajax',
            method: 'GET'
        }).done(function (data) {
            const div = document.createElement('div');
            div.innerHTML = data;
            document.body.insertBefore(div, document.body.firstChild);
            document.getElementById('mdp-disable-preview').addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                document.cookie = 'mdp-project=0;path=/';
                window.location = window.location.pathname;
            });
        }).fail(function (err) {
            console.log(err);
        });
    }
    document.cookie.split(';').filter(function (cookie) {
        return /mdp-project=\d/g.test(cookie);
    });
    if (cookie.length) {
        const project = cookie[0].split('=');
        if (project !== 0) {
            getProjectHtml();
        }
    }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment