Skip to main content

· 2 min read
Tony Woo

In this article, we'll learn what shallow and deep copying is, and the best way to deep copy an object in JavaScript.

Shallow Copying vs Deep Copying

In a reassignment operation involving primitive data types such as strings, numbers and booleans, the original variable is copied by JavaScript.

For example, consider the following code:

let x = 3;
y = x; // x is copied into y

y++; // y is incremented

console.log(y); // now 4
console.log(x); // still 3

In this case, the value 3 is copied into y and then x is disconnected from y. So mutating y does not affect x.

Conversely, with non-primitive data types like arrays and objects, only a reference to the values is passed. So when the copy is mutated, the original also gets mutated. This is also known as shallow copying.

let adam = { name: 'Adam' };

let jason = adam;
jason.name = 'Jason';

console.log(adam.name); // outputs "Jason"
console.log(jason.name); // outputs "Jason"

If we instead want to copy an object so that we can modify it without affecting the original object, we need to make a deep copy.

5 Ways To Deep Copy Objects in JavaScript.

In JavaScript, we can perform a copy on objects using the following methods:

MethodProsCons
shallow copy with =clear and direct, the defaultonly shallow copies objects
JSON.stringify() and JSON.parse()deep copies nested objectsdoesn't copy functions
Object.assign()copies the immediate members of an object—including functionsdoesn't deep copy nested objects
the ... spread operatorsimple syntax, the preferred way to copy an objectsdoesn't deep copy nested objects
Lodash cloneDeep()clones nested objects including functionsadds an external dependency to your project

Conclusion

As you've seen, there are a number of ways to copy a variable in JavaScript. None of them is perfect for every occasion, so you'll have to be careful to chose the best method for each situation.

· One min read
Sébastien Lorber
Yangshun Tay

Docusaurus blogging features are powered by the blog plugin.

Simply add Markdown files (or folders) to the blog directory.

Regular blog authors can be added to authors.yml.

The blog post date can be extracted from filenames, such as:

  • 2019-05-30-welcome.md
  • 2019-05-30-welcome/index.md

A blog post folder can be convenient to co-locate blog post images:

Docusaurus Plushie

The blog supports tags as well!

And if you don't want a blog: just delete this directory, and use blog: false in your Docusaurus config.

· 2 min read
Tony Woo

React Query is often described as the missing data-fetching library for React, but in more technical terms, it makes fetching, caching, synchronizing and updating server state in your React applications a breeze.

Examples
import * as React from 'react';
import { FaCheckCircle, FaPlusCircle, FaMinusCircle, FaBook, FaTimesCircle } from 'react-icons/fa';
import Tooltip from '@reach/tooltip';
import { useMutation, queryCache, useQuery } from 'react-query';
import { client } from 'utils/api-client';
import * as colors from 'styles/colors';
import { CircleButton, Spinner } from './lib';

function StatusButtons({ user, book }) {
const { data: listItems } = useQuery({
queryKey: 'list-items',
queryFn: () => client(`list-items`, { token: user.token }).then((data) => data.listItems),
});
const listItem = listItems?.find((li) => li.bookId === book.id) ?? null;

const [remove] = useMutation(({ id }) => client(`list-items/${id}`, { method: 'DELETE', token: user.token }), { onSettled: () => queryCache.invalidateQueries('list-items') });

const [create] = useMutation(({ bookId }) => client(`list-items`, { data: { bookId }, token: user.token }), { onSettled: () => queryCache.invalidateQueries('list-items') });

const [update] = useMutation(
(updates) =>
client(`list-items/${updates.id}`, {
method: 'PUT',
data: updates,
token: user.token,
}),
{ onSettled: () => queryCache.invalidateQueries('list-items') },
);

return (
<React.Fragment>
{listItem ? Boolean(listItem.finishDate) ? <TooltipButton label='Unmark as read' highlight={colors.yellow} onClick={() => update({ id: listItem.id, finishDate: null })} icon={<FaBook />} /> : <TooltipButton label='Mark as read' highlight={colors.green} onClick={() => update({ id: listItem.id, finishDate: Date.now() })} icon={<FaCheckCircle />} /> : null}
{listItem ? <TooltipButton label='Remove from list' highlight={colors.danger} onClick={() => remove({ id: listItem.id })} icon={<FaMinusCircle />} /> : <TooltipButton label='Add to list' highlight={colors.indigo} onClick={() => create({ bookId: book.id })} icon={<FaPlusCircle />} />}
</React.Fragment>
);
}

export { StatusButtons };

· One min read
Tony Woo

The DBCC CHECKIDENT management command is used to reset identity counter. The command syntax is:

Syntax
DBCC CHECKIDENT (table_name [, { NORESEED | { RESEED [, new_reseed_value ]}}])
[ WITH NO_INFOMSGS ]
Example
DBCC CHECKIDENT ('[NameofTable]', RESEED, 0);
GO

It was not supported in previous versions of the Azure SQL Database but is supported now.

· 8 min read
Paul Orac

Preparing for a job interview is always a daunting task. Most likely you don’t know exactly what you’ll be asked and nerves can easily take over, making you forget even your own name. I’ve compiled 21 Node.js questions for job interviews that go from very simple stuff to some more technically advanced topics to help you in the process.

· One min read
Gao Wei

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque elementum dignissim ultricies. Fusce rhoncus ipsum tempor eros aliquam consequat. Lorem ipsum dolor sit amet